使用Moq模拟方法的某些部分

克里斯

我是Moq的新手,我想模拟我方法的某些部分来测试业务逻辑,但是模拟GetCountry方法时遇到了问题。下面是我用作示例的代码。

public class Class1
    {
        public void Process()
        {

            MyClass foo = new MyClass();
            var o = foo.GetCountry(); //I would like to mock this part.

            //Business Logic here
        }

    }

public class  MyClass : IFoo
{

    public List<string> GetCountry()
    {
        //Get the data from Database.. someone will do this
        throw new NotImplementedException();
    }
}

以下是我使用的测试代码。

[TestMethod]
public void TestMethod2()
{
            var mock = new Moq.Mock<IFoo>();
            mock.Setup(m => m.GetCountry()).Returns(new List<string> { "America", "Philippines", "Japan" });
            ClassLibrary1.Class1 foo = new ClassLibrary1.Class1();
//still called the not implemented exception
            foo.Process();

}
网络

您的代码当前没有一种简单的方法可以将一种实现替换为另一种实现。试试这个方法:

public class Class1
{
    // Instead of using a concrete class, use an interface
    // also, promote it to field
    IFoo _foo;

    // Create a constructor that accepts the interface
    public Class1(IFoo foo)
    {
        _foo = foo;
    }

    // alternatively use constructor which provides a default implementation
    public Class1() : this(new MyClass())
    {
    }

    public void Process()
    {
        // Don't initialize foo variable here
        var o = _foo.GetCountry();
        //Business Logic here
    }
}

如果您有这样的设置,则可以很容易地使用您的代码来模拟它:

[TestMethod]
public void TestMethod2()
{
    var mock = new Moq.Mock<IFoo>();
    mock.Setup(m => m.GetCountry()).Returns(new List<string> { "America", "Philippines", "Japan" });
    // Pass mocked object to your constructor:
    ClassLibrary1.Class1 foo = new ClassLibrary1.Class1(mock.Object);
    foo.Process();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章