validate MOQ unit test method return value

天涯浪子 提交于 2020-01-05 03:35:07

问题


I have the below class and test class written using Moq:

public class Mytest : testin
{
    public int getId(int id)
    {
      int s = 2;
      return s;
    }

}

test class:

private Mock<testin> _mock;

[TestInitialize]
public void Setup()
{
    _mock = new Mock<testin>();

}

[TestMethod]
public void returngetId()
{

    // Build up our mock object

    _mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1)

}

I'm returning 2 from the function and in unit test cases checking for the value 1. As per my understanding the test cases should fail. But im getting success message. How i can validate the return value is exactly what im expecting? I want to fail the test if it returning other than 1.


回答1:


Your current setup will skip the method's execution, and instead "blindly" return 1. You should not mock the method if you wish it to be executed. If you remove the setup line, your test cases will indeed fail. In general, you should only mock a method if you need it to NOT be executed.


To clarify:

The line _mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1) configures your mock object so that whenever you call the getId method, instead of executing it, the value 1 will always be returned. So, the following test would pass:

[TestMethod]
public void returngetId_Always1()
{
    // ... Build up our mock object
    _mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1);
    Assert.AreEqual(1, _mock.Object.getId("foo"));
    Assert.AreEqual(1, _mock.Object.getId("bar"));
}

In order to get the actual implementation of the method to be invoked from within the mock, you have to mock the class, not the interface, with the following configuration:

[TestMethod]
public void returngetId_CallBase()
{
    var mock = new Mock<MyTest>() { CallBase = true };
    // add other method setups here. DO NOT setup the getId() method.
    Assert.AreEqual(2, _mock.Object.getId("foo"));
    Assert.AreEqual(2, _mock.Object.getId("bar"));
}

This will allow the mock to defer to the base implementation for any methods for which a mocking setup has not been provided.



来源:https://stackoverflow.com/questions/38738511/validate-moq-unit-test-method-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!