Unit Testing - Creating object under test in TestMethod vs TestInitialize
Currently I'm writing my unit tests by creating the object under test
within each TestMethod. The main reasons for doing this is to promote
self-containment, ease of readability/debugging and also possibly tailor
the dependencies during construction.
public class MyClass
{
public MyClass(ISomeService serviceA, ISomeOtherService serviceB)
{
...
}
}
[TestMethod]
public void it_should_do_something()
{
var myClass = new (serviceA, serviceB);
MyClass.DoSomething();
...
}
However this is becoming a maintenance nightmare, especially when there
may be many tests on the class and I want to add another dependency to the
constructor. It requires me to change each line of construction in my test
classes.
I'm looking to keep things DRY by initialising the object in a
TestInitialize method, which will improve maintenance whilst still keep
the self-containment aspect.
private MyClass _myClass;
[TestInitialize]
public void Init()
{
_myClass = new (serviceA, serviceB);
}
The only downsides I can see to doing this is that I may need to
reinitialise the object if I need a different set of dependencies to be
injected. It may also be slightly less clear to read/debug to another
developer looking at the code for the first time. Are there any other
negatives to this approach that I'm not thinking of?
What is the best practice for this scenario?
Is it bad practice to initialise the class outside of the TestMethod?
Should I favour maintenance and the DRY principle, or keep things
self-contained for readability/logical purposes?
No comments:
Post a Comment