We continue our series of post about writing maintainable test , always looking about the advice in the book of Roy Osherove The Art Of Unit Testing
Anti Pattern Hidden Test Call
This anti pattern is about calling one test inside another test , we agree that this is an explicit dependency and an unit test ( wchich should run in his world ) should not know the existence of another test.
Code Example
the code below is from the book himself , written in C#, if you do not do C# , do not worry , the code talks very well
[TestFixture]
public class HiddenTestCall
{
private LogAnalyzer logan;
[Test]
public void CreateAnalyzer_GoodNameAndBadNameUsage()
{
logan = new LogAnalyzer();
logan.Initialize();
bool valid = logan.IsValid("abc");
Assert.That(valid, Is.False);
CreateAnalyzer_GoodFileName_ReturnsTrue();
}
[Test]
public void CreateAnalyzer_GoodFileName_ReturnsTrue()
{
bool valid = logan.IsValid("abcdefg");
Assert.That(valid, Is.True);
}
}
Look like the first Test calls the second test.
So the patterns about this are:
Trying to remove duplication : A developer try to be DRY in writing his tests
Laziness about separating his tests : Yes we can be sometimes lazy to separate our tests in the name of i should finish it quickly
... and the solutions to these patterns are:
Trying to remove duplication : refactor
the code you don’t want to write twice into a third method that both your test and the other test callLaziness About Separating the tests: Again ( sometimes Roy is so funny ) look what he said If you’re too lazy to separate your tests, think of all the extra work you’ll have to do if you don’t separate them. Try to imagine a world where the current test you’re writing is the only test in the system, so it can’t rely on any other test.
Thanks for reading. Imagine a better world for your Unit test :)
Top comments (0)