Avoid Test Code in Production

Have you ever seen code like that in Listing 5-3?

Listing 5-3: Example of test code in production

public class MyClass {  private boolean testing = false;  public void doSomething() {    if (testing) {      // Mock something up    } else {      // Run the real code    }  }}

I’m sure you have. Unfortunately, something like this or one of its variations exists in most code bases. Let’s go over all the things that are wrong with this from a software-verification point of view.

First, how is testing set? I may have omitted a setter that would allow directly controlling the behavior through the interface. That would probably be the safest way to manage it. I’ve also seen people use a toggle ...

Get Quality Code: Software Testing Principles, Practices, and Patterns 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.