Tom Cruise Tom Cruise - 3 months ago 25
ASP.NET (C#) Question

validate MOQ unit test method return value

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.

Answer

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.

Comments