I noticed some duplicate code in a codebase I am working on that appended a filename to a directory path, so I decided to refactor it into its own method. The application I am working on is not well tested, however; I just set up the first unit tests on it two days ago, so I am very concerned to get as much code under test as possible whenever I touch it.
So I began to write a unit test like this (pseudocode):
Directory directory("a")
Expect(directory.prependPathToFilename("b")).toBeEqualTo("a/b")
However, I then remembered that the application is cross-platform. So I thought about this:
Directory directory("a")
String separator = "/" if (platform is *nix) else ""
Expect(directory.prependPathToFilename("b")).toBeEqualTo("a" + separator + "b")
But I remembered that Roy Osherove says in section 7.1.2 (“Avoiding logic in tests”) of The Art of Unit Testing (178):
If you have any of the following inside a test meethod, your test contains logic that should not be there:
switch
,if
, orelse
statements
foreach
,for
orwhile
loopsA test that contains logic is usually testing more than one thing at a time, which isn’t recommended, becauset he test is less readable and more fragile. But test logic also adds complexity that may contain a hidden bug.
Now, it does not seem that in this case I am testing more than one thing at a time. Would this be a case of an acceptible logic block in a test? Is there a pattern for cleanly testing behaviors/results that are expected to be different on different platforms?
2
It is disputed how religious you have to be about unit testing – surely there is some value to tests even if they violate some of the precepts of the Wise Elders of testing (certainly more value than not having them!).
However, in this instance you need not break the rules if you don’t want to. Note that your test is only testing one of the possible separators, because by definition it runs only on one platform. If you make the platform-detecting routine mockable, you can write different tests and inject different pseudo-platforms into them. Each of the tests then need not have any logic in it, and you achieve greater coverage at the same time.
To keep your unit test clean and simple, you could extend the test library by adding a new assertion for paths. This new assertion would abstract from the different path separators. Your test would then look like
Directory directory("a")
Expect(directory.prependPathToFilename("b")).toBeSamePathAs("a/b")
and – depending on implementation – work identically when using
Directory directory("a")
Expect(directory.prependPathToFilename("b")).toBeSamePathAs("ab")