I am attempting to test the Index
action of a controller. The action uses AutoMapper to map a domain Customer
object to a view model TestCustomer
I would probably separate the coupling between AutoMapper
and the controller by introducing an abstraction:
public interface IMapper
{
TDest Map(TSource source);
}
public CustomerToTestCustomerFormMapper: IMapper
{
static CustomerToTestCustomerFormMapper()
{
// TODO: Configure the mapping rules here
}
public TestCustomerForm Map(Customer source)
{
return Mapper.Map(source);
}
}
Next you pass this into the controller:
public HomeController: Controller
{
private readonly IMapper _customerMapper;
public HomeController(IMapper customerMapper)
{
_customerMapper = customerMapper;
}
public ActionResult Index()
{
TestCustomerForm cust = _customerMapper.Map(
_repository.GetCustomerByLogin(CurrentUserLoginName)
);
return View(cust);
}
}
And in your unit test you would use your favorite mocking framework to stub this mapper.