Mock objects - Setup method - Test Driven Development

Unit TestingTddMockingMoq

Unit Testing Problem Overview


I am learning Test Driven Development and trying to use Moq library for mocking. What is the purpose of Setup method of Mock class?

Unit Testing Solutions


Solution 1 - Unit Testing

The default behaviour of a Moq Mock object is to stub all methods and properties. This means that a call to that method/property with any parameters will not fail and will return a default value for the particular return type.

You call Setup method for any or all of the following reasons:

  • You want to restrict the input values to the method.

    public interface ICalculator { int Sum(int val1, val2); }

    var mock = new Mock(); mock.Setup(m=>m.Sum( It.IsAny(), //Any value 3 //value of 3 ));

The above setup will match a call to method Sum with any value for val1 and val2 value of 3.

  • You want to return a specific value. Continuing with ICalculator example, the following setup will return a value of 10 regardless of the input parameters:

    var mock = new Mock(); mock.Setup(m=>m.Sum( It.IsAny(), //Any value It.IsAny() //Any value )).Returns(10);

  • You want to use Mock<T>.VerifyAll() after you setups to verify that all previous setups have been called (once).

    var mock = new Mock(); mock.Setup(m=>m.Sum( 7, //value of 7 3 //value of 3 ));

    mock.Setup(m=>m.Sum( 5, //value of 5 3 //value of 3 ));

    mock.VerifyAll();

The above code verifies that Sum is called twice. Once with (7,3) and once with (5,3).

Solution 2 - Unit Testing

Setup method is used to set expectations on the mock object For example:

mock.Setup(foo => foo.DoSomething("ping")).Returns(true);

Here you are setting the DoSomething method on mock object. You are saying, when the parameter is "ping", the method returns true.

Now this object can further act as a mock or a stub depending on your usage. If you want to use it in state based testing, it can act as a stub. If you want to use it in behavior based testing, it can act as a mock. In behavior testing, you will call the verify method on the mock object to assert that the method was called with "ping" parameter

Further refer these links:

http://martinfowler.com/articles/mocksArentStubs.html

http://code.google.com/p/moq/wiki/QuickStart

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmeckrtView Question on Stackoverflow
Solution 1 - Unit TestingIgor ZevakaView Answer on Stackoverflow
Solution 2 - Unit TestingP.KView Answer on Stackoverflow