I have settled with this type of structuring of unit tests.
Basic idea is that there is a base test class for the tested class, and a subclass for every tested method. They use the mocks and everything from the base test class, the point being that the test would remain small, and you don't have to create everything in the test.
Idea for this came from Haacked http://haacked.com/archive/2012/01/02/structuring-unit-tests.aspx/
public class HomeControllerTest
{
protected HomeController Controller;
protected Mock<IUnitOfWork> UnitOfWork;
protected Mock<IRepositoryOne<Entity>> Repository;
protected Fixture Fixture;
public HomeControllerTest()
{
UnitOfWork = new Mock<IUnitOfWork>();
Repository = new Mock<IRepositoryOne<LoanRequirement>>();
Controller = new HomeController(
UnitOfWork.Object,
Repository.Object);
Fixture = new Fixture();
}
public class GetHomeMethod : HomeControllerTest
{
[Fact]
public void ReturnsEntityDataFromDatabase()
{
Repository.Setup(x => x.GetId(1)).Returns(new Entity());
var result = Controller.GetOne(1) as OkNegotiatedContentResult<HomeModel>;
Assert.NotNull(result);
var model = result.Content;
var entityToModel = Mapper.Map<HomeModel>(entity);
Assert.Equal(model, entityToModel,HomeModel.HomeModelComparer);
}
}
public class PostHomeMethod : HomeControllerTest
{
// Test the post method
}
public class PutHomeMethod : HomeControllerTest
{
// Test the put method
}
}
I ask in general is there anything wrong about doing it like this, any dangers that I don't spot? Any comments are welcome. Main point for asking a question like this is to polish my unit tests, so they would be even more organized.