Some of our business logic classes require quite a few dependencies (in our case 7-10). As such when we come to unit test these the creation become quite complex.
In most tests these dependencies are often not required (only some dependencies are required for particular methods).
As a result unit tests often require a significant number of lines of code to mock up these useless dependencies (which can’t be null because of null checks).
For example:
[Test]
public void TestMethodA()
{
var dependency5 = new Mock<IDependency1>();
dependency5.Setup(x => x. // some setup
var sut = new Sut(new Mock<IDependency1>().Object,
new Mock<IDependency2>().Object,
new Mock<IDependency3>().Object,
new Mock<IDependency4>().Object,
dependency5);
Assert.SomeAssert(sut.MethodA());
}
In this example almost half the test is taken up creating dependencies which aren’t used. I’ve investigated an approach where I have a helper method.
[Test]
public void TestMethodA()
{
var dependency5 = new Mock<IDependency1>();
dependency5.Setup(x => x. // some setup
var sut = CreateSut(null, null, null, null, dependency5);
Assert.SomeAssert(sut.MethodA());
}
private Sut CreateSut(IDependency1 d1, IDependency2 d2...)
{
return new Sut(d1 ?? new Mock<IDependency1>().Object,
d2 ?? new Mock<IDependency2>().Object,
}
But these often grow very complicated very quickly.
What is the best way to create these BLL classes in test classes to reduce complexity and simplify tests?
You construct them which ever way you need them constructed, and then you apply standard good practices to the resulting code – DRY, refactoring, single-responsibility, etc.
There is a widespread impression that it is bad to spend too much effort on testing code because of a vague belief that it isn’t “real” code. This is very wrong.
Test code belongs to your code base and contributes to its excellence just as much as every other kind of deliverable. The fact that it isn’t (normally) shipped to the customer is irrelevant. If it’s worth writing test code because it saves time overall, then it’s worth writing well-designed testing code because it saves even more time overall.
Therefore, there is absolutely nothing wrong with having helper classes only used in unit tests, or inventing mock objects more complicated than the mocking framework of your preference can auto-generate, if that’s what’s needed to get things under test. Indeed, this is the best way by definition.
a few things:
1) 10 dependencies is too much. you are probably missing a layer of abstraction.
see:
https://stackoverflow.com/questions/2420193/how-to-avoid-dependency-injection-constructor-madness
http://blog.ploeh.dk/2010/02/02/RefactoringtoAggregateServices/
2)there are automocking frameworks like:
https://automock.codeplex.com/
3) theres also https://autofixture.codeplex.com/ to make your life easier
3