Chapter 11. Test-driven development

 

This chapter covers

  • The benefits of practicing test-driven development (TDD)
  • The red-green-refactor lifecycle at the heart of TDD
  • A brief intro to JUnit, the de facto Java testing framework
  • The four types of test double: dummy, fake, stub, and mock
  • Testing against an in-memory database for your DAO code
  • Mocking subsystems with Mockito
  • Using ScalaTest, the testing framework for Scala

Test-driven development (TDD) has been part of the software development industry for quite some time. Its basic premise is that you write a test before writing the code that actually provides the implementation, and then you refactor that implementation as needed. For example, in order to write an implementation of concatenating two String objects ("foo" and "bar"), you’d write the test first (testing the result must equal "foobar") to ensure that you know your implementation is correct.

Many developers already know about the JUnit testing framework and use it on a semi-regular basis. But more often than not, they’re writing tests after they’ve written the implementation, and therefore are losing out on some of the major benefits of TDD.

Despite its seeming pervasiveness, many developers don’t understand why they should be doing TDD. The question for many developers remains, “Why write test-driven code? What’s the benefit?”

11.1. TDD in a nutshell

11.2. Test doubles

11.3. Introducing ScalaTest

11.4. Summary