|
![]() |
Books: Pragmatic Unit Testing in Java, Agile Java, Modern C++ Programming with TDD, Essential Java Style, Agile in a Flash. Contributor, Clean Code.
Jeff Langr wrote:I seek to test "through the interface" when unit testing. For your lambda example, I do think it's best extracted as a separate method and tested directly. I might end up with the following cases, each of which is a single-line test:
returnsEmptySetWhenListEmpty
returnsOnlyOddNumbers
returnsOnlyNumbersAboveThreshold
eliminatesDuplicates
There are more simple variants I could code if I felt I needed the confidence.
I'm not testing a lambda--that's an implementation detail. I could re-code your expression with classic loop structures, and it should pass the same tests I designed around the interface to the desired behavior.
Jeff Langr wrote:The code will get more complex, most likely! That's where having tests really pays off--they will prevent you from breaking stuff that already works when you make changes. The more complex the code, the more useful it is to have the confidence that the tests can give you.
Jeff Langr wrote:Separating things to separate Predicates can both make it easier to test and also to understand client code. I've not seen it be a problem. You might find a bit of additional reuse, and therefore shrink your code, by doing so.
Roel De Nijs wrote:A simple example: assume you'll have a utility method isEmpty(String s) which returns true if s is null, empty or whitespace; false otherwise. And you need to test this method:Will you write tests for empty type values like null, "" and " "? Or do you mock the isEmpty call returning true if you pass "ty0" and false with all other values?
Books: Pragmatic Unit Testing in Java, Agile Java, Modern C++ Programming with TDD, Essential Java Style, Agile in a Flash. Contributor, Clean Code.
Jeff Langr wrote:Right--if you assume that isEmpty is already tested (I wrote unit tests for it elsewhere), the job in testing the create method is to verify the two possible paths based on the two possible outcomes of the if conditional. As you suggest, you could mock the static (if you were using, for example, PowerMock). You could also set the value of type to a value that answers false for the conditional for one test, and to a value that answers true for a second test. Those two tests, perhaps named:
createReturnsNullWhenTypeIsEmpty
createReturnsAnimalWhenTypeNotEmpty
are sufficient, since isEmpty is already tested. Any more tests around how type might be "empty" would be redundant.
Books: Pragmatic Unit Testing in Java, Agile Java, Modern C++ Programming with TDD, Essential Java Style, Agile in a Flash. Contributor, Clean Code.