Tag Archives: unit testing

Autofixture: Do() not working? You forgot Without()

I use AutoFixture for generating test data in my unit tests. AutoFixture has served me well, but the documentation doesn’t give great examples of how to use it. The “cheat sheet” has links to the authors blogs, and if you’re not careful you won’t find everything you need. It’s sometimes easy to miss those links.

The other day, I was trying to generate a POCO that had a string property, and I wanted that string property to be constrained to a list of valid values. Since I obviously didn’t want to customize the string type across my entire fixture, I instead customized the parent type with the Do method. I wanted to pass in an action that would randomly select from the list pre-defined values and then assign it to the string property in my class instance. The code was straight-forward, but the string was still being populated with the default AutoFixture value.

Read more »

Using delegates for loose coupling and easy unit testing

In a typical ASP.NET MVC or WebApi project, controller actions often do nothing more than make a service call, map the returned domain object to a view model, and either render a view with the model or simply return it for the framework to serialize as JSON. Using AutoMapper, a simplified WebApi controller action may look something like

public EmployeeViewModel GetEmployee(string employeeName)
{
  var employee = _employeeService.GetByName(employeeName);
  var viewModel = Mapper.Map<EmployeeViewModel>(employee);
  return viewModel;
}

This is a pretty common but difficult to test pattern because of the static Mapper dependency. You can’t actually unit test the controller action without having a properly (or at least minimally) configured static Mapper. New versions of AutoMapper provide different ways to solve this problem, like the injectable IMapper interface, but I want to demonstrate another method to reduce coupling and ease unit testing.

In this entry, I’ll demonstrate how to get rid of the static Mapper dependency without using the IMapper interface, which exposes several overloads to map one data type to another, or creating your own interface that serves a similar purpose. Instead, we’ll inject a delegate whose signature is very expressive.

public delegate TDest MapperFunc<in TSrc, out TDest>(TSrc source);

Read more »