validate MOQ unit test method return value

前端 未结 1 733
你的背包
你的背包 2021-01-23 17:39

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


        
相关标签:
1条回答
  • 2021-01-23 17:52

    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.

    0 讨论(0)
提交回复
热议问题