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 books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.