Friday, 13 January 2012

Some thoughts on mocking


I find the mocking is one of the most tricky parts of unit testing. Where I work we use Moq which is a nice, simple mocking framework. It may not be as powerful as some of the commercial frameworks but it does the job. 

Roy Osherove suggests that a single unit test should only have one mock but often find myself creating several mocks. Perhaps the class under test has too many dependencies or perhaps I'm creating mocks where they are not needed or perhaps it's simply due to the limitations of the mocking framework. Whichever it is I'd like to get it clear in my head. Take the following example, it has three types of call that you're likely to mock when unit testing a method:

public void DoSomeStuff(User user) 
{    
   this.VerifySomeImportantThings(user);                                // 1
   int returnValue = someRepository.GetImportantValue();      // 2                                 
   someRespository.Save(user);                                                 // 3
}

  1. Methods called on the same class under test always have to be mocked when using Moq because you have to tell the framework not to call their code. Also if they were tested it would be duplication as there should be separate unit tests for those methods
  2. Method calls on dependencies which return a value only need to be mocked if you care about the return value or any exceptions thrown
  3. Method calls on dependencies which do not return a value only need to be mocked if exceptions need to be tested

No comments:

Post a comment