简体   繁体   English

Moq设置单元测试

[英]Moq setup unit test

I have a simple method like: 我有一个简单的方法,如:

public class MyService : IMyService
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}

public interface IMyService
{
    int Add(int x, int y);
}

and I wrote a unit test with for that method: 我为该方法编写了一个单元测试:

public void PassingTest()
{
    var mock = new Mock<IMyService>();

    mock.Setup(x => x.Add(It.IsAny<int>(), It.IsAny<int>())).Returns<int, int>((x, y) => { return x + y; });

    var svc = mock.Object;

    var result = svc.Add(3, 3);
    var result2 = svc.Add(2, 5);
    result.Should().Be(6);
    result2.Should().Be(7);
}

Is this code is okay? 这段代码还可以吗? Why should I must write Returns statement which is almost the same like whole method ? 为什么我必须编写与整个方法几乎相同的Returns语句?

You would only do something like this if IMyService was to be used as a dependency to another class that you wanted to test. 如果IMyService用作您想要测试的另一个类的依赖项,那么您将只执行此类操作。 If IMyService is the system under test then you wouldn't as you don't mock the system you are trying to test. 如果IMyService是被测试的系统,那么你不会因为你没有模拟你想要测试的系统。 You use an actual instance of the target class. 您使用目标类的实际实例。

Let's say in a very simplified example, we have a class like this. 让我们说一个非常简单的例子,我们有一个这样的类。

public class SomeClass {
    public SomeClass(IMyService service) {
        this.service = service;
    }
    private readonly IMyService service;

    public int SomeMethodThatUsesMyService(int input) {
        int someConstant = 10;

        var result = service.Add(someConstant, input);
        return result;
    }
}

If the implementation of IMyService does some processing that is IO dependent and is very difficult to test on its own. 如果IMyService的实现执行一些依赖于IO的处理,并且很难自行测试。 Then a mocking IMyService would make sense for trying to test that class. 然后, IMyService对于尝试测试该类是有意义的。

[Fact]
public void Given_Input_SomeMethodThatUsesMyService_Should_Increase_By_Ten() {
    //Arrange
    var expected = 14;

    var mock = new Mock<IMyService>();

    mock.Setup(x => x.Add(It.IsAny<int>(), It.IsAny<int>())).Returns<int, int>((x, y) => { return x + y; });

    var svc = mock.Object;

    var sut = new SomeClass(svc);

    //Act
    var result = sut.SomeMethodThatUsesMyService(4);

    //Assert
    result.Should().Be(expected);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM