How best to construct our test subjects in unit tests?

Posted by Liath on Programmers See other posts from Programmers or by Liath
Published on 2014-08-19T12:09:33Z Indexed on 2014/08/19 16:29 UTC
Read the original article Hit count: 156

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?

© Programmers or respective owner

Related posts about .NET

Related posts about unit-testing