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

时间:2015-03-15 07:49:22

标签: c# .net 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();

}

1 个答案:

答案 0 :(得分:3)

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

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();
}