I’ve got a Coordinate class, which has an add(Coordinate) method. When writing unit tests for this class, I’ve got tests to assertEqual a result:
a = Coordinate(1,2,3)
b = Coordinate(5,6,7)
result = a.add(b)
assertEqual(result.x, 6)
assertEqual(result.y, 8)
assertEqual(result.z,10)
I can ‘fake’ this rather easily:
def add(self, other):
return Coordinate(6,8,10)
This is the simplest solution to the test failure. The next step is to write a second test which prevents me from faking it in this manner. I could either:
- write another
assertEqualtest with different numbers (so faking theCoordinate(6,8,10)doesn’t pass, or - Write an
assertNotEqualtest with two different inputs, ensuring that the result isn’t6,8,10.
If I write an assertEquals test, I’ve then got two tests that look very, very similar. Is this a problem? If I saw code that similar in the project, I’d be tempted to refactor it. Should I do this for the test code too – and, if so, won’t this mean every pair of tests will end up being refactored?
If I write an assertNotEqual, the test is only testing for “fake results” – which I am very sure won’t ever come up from an algorithmic error. In essence, once I write the test, stop faking the result so both tests pass, the assertNotEquals test can be safely removed, and I will still have confidence in the code – so I’d write the test, fix the fake, remove the test, which seems rather silly.
What should I be doing in this situation?
Another assertEqual test with different numbers will be good enough. If possible, take a “borderline” or uncommon case, like :
An AssertNotEqual test would be absurd and not intuitive for the reader IMO.
In any case, I wouldn’t worry too much about this kind of tests. As a reader it’s really obvious that the developer who wrote them just wanted to test a couple of cases, and it would take a real refactoring extremist to want to refactor them. I mean, it’s only 2 tests with almost no duplication, the intent is obvious and it’s not like you have to rewrite 300 lines of code when the object changes…