Chapter 12Test-Driven Development

By now you’ve no doubt noted that it’s hard to write unit tests for some code. This difficult legacy code grows partly from a lack of interest in unit testing. In contrast, the more you consider how to unit-test the code you write, the more likely you are to end up with code that’s easier to test. (“Well, duh!” respond Pat and Dale simultaneously.)

Consider always thinking first about how you will test the code you’re about to write. Rather than slap out some code and then figure out how to test it, design a test that describes the code you want to write, then write the code. This reversed approach might seem bizarre or even impossible, but it’s the core element in the unit-testing practice of test-driven ...

Get Pragmatic Unit Testing in Java 8 with JUnit now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.