Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock objects - Setup method - Test Driven Development

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

like image 281
meckrt Avatar asked Jul 05 '10 13:07

meckrt


People also ask

What is mock object in TDD?

Mocking is the creation of an object that mimics another and sets expectations concerning its behavior. In testing, mocking replicates the behavior of a service, object, or process. There are a number of benefits that result from replacing an object with a mock for testing purposes.

What are mock objects in testing?

Mock objects are a type of test double. They replace production objects to make for easier and more reliable testing practices. If developers want to use mock objects as part of their testing process, they need to be aware of potential pitfalls that can harm their applications' code.

What is setup in mock?

Setup method is used to set expectations on the mock object For example: mock. Setup(foo => foo. DoSomething("ping")). Returns(true);


1 Answers

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<ICalculator>(); mock.Setup(m=>m.Sum(   It.IsAny<int>(), //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<ICalculator>(); mock.Setup(m=>m.Sum(   It.IsAny<int>(), //Any value   It.IsAny<int>()  //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<ICalculator>(); 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).

like image 74
Igor Zevaka Avatar answered Sep 22 '22 11:09

Igor Zevaka