具有多个接口的单元测试

时间:2018-05-21 20:47:50

标签: c# unit-testing moq vs-unit-testing-framework

我有一个Web API项目,其中包含从API Controller调用的以下服务类。我想使用Moq框架为下面的类编写单元测试用例。如何使用Moq构建多个接口?如果不可能使用Moq,还有其他框架吗?

public class MyService : IMyService
{
    private readonly IInterface1 _interface1;
    private readonly IInterfaces2 _interface2;
    private readonly IInterface3 _interface3;

    public MyService(IInterface1 interface1,IInterface2 interface2,IInterface3 interface3)
    {
        _interface1=interface1;
        _interface2=interface2;            
        _interface3=interface3;
    }

    public SomeModel MyMethod1(1Model model)
    {
        //do something here.... 
    }

    public SomeMode2 MyMethod2(Model2 model)
    {
        //do something here.... 
    }

    public SomeMode3 MyMethod3(Model3 model)
    {
        //do something here.... 
    }
}

2 个答案:

答案 0 :(得分:2)

想象一下,你有这些接口:

public interface IOne
{
    int Foo();
}

public interface ITwo
{
    int Foo(string str);
}

你有一个依赖于以上接口的类:

public class Some
{
    private readonly IOne one;
    private readonly ITwo two;

    public Some(IOne one, ITwo two)
    {
        this.one = one;
        this.two = two;
    }

    public void Work()
    {
        // Uses one and two
    }
}

现在你要测试Work()方法,并且想要模拟依赖项,这里是如何:

// Arrange
// Let's set up a mock for IOne so when Foo is called, it will return 5
var iOneMock = new Mock<IOne>();
iOneMock.Setup(x => x.Foo()).Returns(5);

// Let's set up the mock for ITwo when Foo is called with any string, 
// it will return 1
var iTwoMock = new Mock<ITwo>();
iTwoMock.Setup(x => x.Foo(It.IsAny<string>())).Returns(1);

var some = new Some(iOneMock.Object, iTwoMock.Object);

// Act
some.Work();

// Assert
// Let's verify iOneMock.Foo was called. 
iOneMock.Verify(x => x.Foo());
// Let's verify iTwoMock.Foo was called with string "One" and was called only once
iTwoMock.Verify(x => x.Foo("One"), Times.Once());

在上面的例子中,我尝试显示采用参数的方法,不带参数的方法,调用验证方法以及调用验证方法一次。这应该给你和想法可用的选项。还有许多其他选择。有关更多信息,请参阅Moq文档。

答案 1 :(得分:0)

您可以使用AutoMoq来解决依赖注入问题。

var mocker = new AutoMoqer();
var myService = mocker.Create<MyService>();
var interface1 = mocker.GetMock<IInterface1>();