0

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 Feb 4 at 19:18
4

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).

  • 1
    That 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 Feb 4 at 9:45
2

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)
0

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.