Scenario
I'm a new developer, using MSTest and I've encountered the following issue:
SomeClassTest // Uses a Fake Widget Controller.
Test Initialize
{
Many lines of code to initialize Fake Widget Controller
}
Test Method
{
Uses fake widget controller
}
AnotherClassTest // Uses same Fake Widget Controller.
Test Initialize
{
Duplicate many lines of code to initialize Fake Widget Controller
}
Test Method
{
Uses fake widget controller
}
Should I copy and paste the initialization code into the new class, or should I create a separate configuration class and instantiate it in each test class that requires it?
Or am I looking at this the wrong way?
-
Think of what will happen when you duplicate that initialization code 20 times, and then have to change the initialization (maybe because of a bug, maybe because of some extensions to the Widget Controller).Doc Brown– Doc Brown2019年02月04日 19:18:25 +00:00Commented Feb 4, 2019 at 19:18
3 Answers 3
Should I copy and paste the initialization code into the new class, or should I create a separate configuration class and instantiate it in each Test Class that requires it?
Test code is just as much code as the code that goes into production. This means that most of the principles that you use for production code also apply to test code. One of those principles is that you should avoid repeating yourself (repeating the same code, with the same purpose, in multiple places).
-
1That being said (and I do agree with you), there is a difference in test code and production code here. Test code has a higher need for code that is readable in a way that the values (rather than the logic) are easily readable. In production code, you often don't care about exact values and work based on hypothesized values ("if A is true then do B") but not in test code ("A is true so B should be done"). Abstracted code is fine but take care to not overly obfuscate it with abstractions.Flater– Flater2019年02月04日 09:45:44 +00:00Commented Feb 4, 2019 at 9:45
Reuse code where possible. BUT!
I've seen simple shared setup code transform into giant custom test frameworks of death over time.
Keep your test code simple and separated, you don't want to have a whole special way of doing things that you have to maintain and debug.
Your tests should follow a simple pattern
#Setup
var data = //get my setup data
var target = new TargetThing()
#Test
var actual = target.MethodUnderTest(data)
#Assert
Assert.AreEqual(actual, expected)
-
Otherwise known as arrange, act, assert.Robbie Dee– Robbie Dee2019年01月31日 15:37:28 +00:00Commented Jan 31, 2019 at 15:37
I don't know what the C# conventions for tests are, being mostly a Java developer, but I would do it like this:
SomeClassTest // Uses a Fake Widget Controller.
Test Initialize
{
Many lines of code to initialize Fake Widget Controller
}
Test Method
{
Uses fake widget controller
}
Second Test Method
{
Uses fake widget controller
}