Friday, March 14, 2014

Verify Times Once

My first WebApi controller test is usually Verify Times Once as show below.

Repo.Verify(x=>x.GetUser(It.IsAny<string>()),Times.Once);


A new member of the team questioned the value of the test. I agreed it was probably more ceremony than a realistic possible regression.
Later in the day I saw the following property in a class.

 public static IFooRepo Repo { get { return _repo ?? (_repo = new FooRepo()); } } 

The code above is tightly coupled.  I prefer loose coupling.  The property is doing the work of the constructor (assuming we are using constructor injection.)  Changing the property from static to a regular class property allows the developer to override the hard coded FooRepo with a mock repo object derived from the IFooRepo interface providing support for testing other methods.  I think we still have a problem with this pattern.  Given a class with more that one property, how will the developer know which properties need setting and which to leave alone? The developer never needs to guess what properties need to be set when the class uses constructor injection.

It might feel like ceremony to perform an obvious test like Verify Times Once, but it ensures loosely coupled code that supports future TDD style tests.