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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x