Project Smells

Smells in This Chapter

       Buggy Tests 260

       Developers Not Writing Tests 263

       High Test Maintenance Cost 265

       Production Bugs 268

Buggy Tests

Bugs are regularly found in the automated tests.

Fully Automated Tests (see page 26 ) are supposed to act as a "safety net" for teams doing iterative development. But how can we be sure the safety net actually works?

Buggy Tests is a project-level indication that all is not well with our automated tests.

Symptoms

A build fails, and a failed test is to blame. Upon closer inspection, we discover that the code being testing works correctly, but the test indicated it was broken.

We encountered Production Bugs (page 268 ) despite having tests that verify the specific scenario in which the bug was found. Root-cause analysis indicates the test contains a bug that precluded catching the error in the production code.

Impact

Tests that give misleading results are dangerous! Tests that pass when they shouldn't (a false negative , as in "nothing wrong here") give a false sense of security. Tests that fail when they shouldn't (a false positive ) discredit the tests. They are like the little boy who cried, "Wolf!"; after a few occurrences, we tend to ignore them.

Causes

Buggy Tests can have many causes. Most of these problems also show up as code or behavior smells. As project managers, we are unlikely to see these underlying smells until we specifically look for them.

Cause: Fragile Test

Buggy Tests may just be project-level symptoms of a Fragile Test (page 239 ). For false-positive test failures, a good place to start is the "four sensitivities": Interface Sensitivity (see Fragile Test ), Behavior Sensitivity (see Fragile Test ), Data Sensitivity (see Fragile Test ) , and Context Sensitivity (see Fragile Test ). Each of these sensitivities could be the change that caused the test to fail. Removing the sensitivities by using Test Doubles (page 522 ) and refactoring can be challenging but ultimately it will make the tests much more dependable and cost-effective.

Cause: Obscure Test

A common cause of false-negative test results (tests that pass when they shouldn't) is an Obscure Test (page 186 ), which is difficult to get right—especially when we are modifying existing tests that were broken by a change we made. Because automated tests are hard to test, we don't often verify that a modified test still catches all the bugs it was initially designed to trap. As long as we see a green bar, we think we are "good to go." In reality, we may have created a test that never fails.

Obscure Tests are best addressed through refactoring of tests to focus on the reader of the tests. The real goal is Tests as Documentation (see page 23 )—anything less will increase the likelihood of Buggy Tests .

Cause: Hard-to-Test Code

Another common cause of Buggy Tests , especially with "legacy software" (i.e., any software that doesn't have a complete suite of automated tests), is that the design of the software is not conducive to automated testing. This Hard-to-Test Code (page 209 ) may force us to use Indirect Testing (see Obscure Test ) , which in turn may result in a Fragile Test .

The only way Hard-to-Test Code will become easy to test is if we refactor the code to improve its testability. (This transformation is described in Chapter 6 , Test Automation Strategy, and Chapter 11 , Using Test Doubles .) If this is not an option, we may be able to reduce the amount of test code affected by a change by applying SUT API Encapsulation (see Test Utility Method on page 599 ).

Troubleshooting Advice

When we have Buggy Tests, it is important to ask lots of questions. We must ask the "five why's" [TPS] to get to the bottom of the problem—that is, we must determine exactly which code and/or behavior smells are causing the Buggy Tests and find the root cause of each smell.

Solution Patterns

The solution depends very much on why the Buggy Tests occurred. Refer to the underlying behavior and code smells for possible solutions.

As with all "project smells," we should look for project-level causes. These include not giving developers enough time to perform the following activities:

  • Learn to write the tests properly
  • Refactor the legacy code to make test automation easier and more robust
  • Write the tests first

Failure to address these project-level causes guarantees that the problems will recur in the near future.

Developers Not Writing Tests

Developers aren't writing automated tests.

Symptoms

We hear that our developers aren't writing tests. Or maybe we have observed Production Bugs (page 268 ) and asked, "Why are so many bugs getting through?", only to be told, "Because we aren't writing tests to cover that part of the software."

Impact

If the team isn't writing automated tests for every piece of software "that could possibly break," it is mortgaging its future. The current pace of software development will not be sustainable over the long haul because the system will be in test debt . It will take longer and longer to add new functionality, and refactoring the code to improve its design will be fraught with peril (so it will happen less and less frequently). This problem marks the beginning of a trip down the proverbial "slippery slope" to traditional paranoid, non-agile development. If that is where we aspire to be, we should stay the course. Otherwise, it is time to take action.

Causes

Cause: Not Enough Time

Developers may have trouble writing tests in the time they are given to do the development. This problem could be caused by an overly aggressive development schedule or supervisors/team leaders who instruct developers, "Don't waste time writing tests." Alternatively, developers may not have the skills needed to write tests efficiently and may not be allocated the time required to work their way up the learning curve.

If time is what the developers need, managers need to adjust the project schedule to give them that time. This extension need be only a temporary adjustment while the developers learn the skills and test automation infrastructure that will enable them to write the tests more quickly. In my experience, once developers have internalized the process, they can write the tests and the code in the same amount of time it once took them to write and debug just the code. The time spent writing the tests is more than compensated for by the time not spent in the debugger.

Cause: Hard-to-Test Code

A common cause of Developers Not Writing Tests, especially with "legacy software" (i.e., any software that doesn't have a complete suite of automated tests), is that the design of the software is not conducive to automated testing. This situation is described in more detail in its own smell, Hard-to-Test Code (page 209 ).

Cause: Wrong Test Automation Strategy

Another cause of Developers Not Writing Tests may be a test environment or test automation strategy that leads to Fragile Tests (page 239 ) or Obscure Tests (page 186 ) that take too long to write. We need to ask the "five why's" [TPS] to find the root causes. Then we can address those causes and get the ship back on course.

Troubleshooting Advice

Project-level smells such as Developers Not Writing Tests are more likely to be detected by a project manager, scrum master, or team leader than by a developer. As managers, we may not know how to fix the problem, but our awareness and recognition of it is what matters. This unique perspective allows managers to ask the development team questions about why they aren't writing tests, in which circumstances, and how long it takes to write tests when they do so. Then managers can encourage and empower the developers to come up with ways of addressing the root causes so that they write all the necessary tests.

Of course, managers must give the developers their full support in carrying out whatever improvement plan they come up with. That support must include enough time to learn the requisite skills and build or set up the necessary test infrastructure. And managers shouldn't expect things to turn around overnight. They might set a process improvement goal for each iteration, such as "20% reduction in code not tested" or "20% improvement in code coverage." These goals should be reasonable and at a high-enough level that they encourage the right behavior, as opposed to just making the numbers look good. (A goal of 205 more tests written, for example, could be achieved without increasing the test coverage one iota simply by splitting tests into smaller pieces or cloning tests.)

High Test Maintenance Cost

Too much effort is spent maintaining existing tests.

Test code needs to be maintained along with the production code it verifies. As an application evolves, we will likely have to revisit our tests on a regular basis whenever we change the SUT classes to add new functionality or whenever we refactor the tests to simplify those classes. High Test Maintenance Cost occurs when the tests become overly difficult to understand and maintain.

Symptoms

Development of new functionality slows down. Every time we add some new functionality, we need to make extensive changes to the existing tests. Developers or test automaters may tell the project manager or coach that they need a "test refactoring/cleanup iteration."

If we have been tracking the amount of time we spend writing the new tests and modifying existing tests separately from the time we spend implementing the code to make the tests pass, we notice that most of the time is spent modifying the existing tests.

Most test maintainability issues are accompanied by other smells, such as the following:

  • A Fragile Test (page 239 ) indicates that tests are too closely coupled to the SUT.
  • A Fragile Fixture (see Fragile Test ) signals that too many tests depend on the same fixture design ( Standard Fixture on page 305 ), which leads to High Test Maintenance Cost .
  • An Erratic Test (page 228 ) may be a sign that a Shared Fixture (page 317 ) is causing our problem.

Impact

Team productivity drops significantly because the tests take so much effort to maintain. Developers may be agitating to "cut and run" (remove the affected tests from the test suites). While writing the production code is mandatory, maintaining the tests is completely optional (at least to the uninformed). If nothing is done about this problem, the entire test automation effort may be wasted when the team or management decides that test automation just "doesn't work" and abandons the tests.

Causes

The root cause of High Test Maintenance Cost is failing to pay attention to the principles described in Chapter 5 , Principles of Test Automation . A more immediate cause is often too much Test Code Duplication (page 213 ) and tests that are too closely coupled to the API of the SUT.

Cause: Fragile Test

Tests that fail because minor changes were made to the SUT are called Fragile Tests . They result in High Test Maintenance Cost because they need to be revisited and "giggled" after all manner of minor changes that really shouldn't affect them.

The root cause of this failure can be any of the "four sensitivities": Interface Sensitivity (see Fragile Test ), Behavior Sensitivity (see Fragile Test ), Data Sensitivity (see Fragile Test ) , and Context Sensitivity (see Fragile Test ). We can reduce the High Test Maintenance Cost by protecting the tests against as many of these sensitivities as possible through the use of Test Doubles (page 522 ) and by refactoring the system into smaller components and classes that can be tested individually.

Cause: Obscure Test

Obscure Tests (page 186 ) are a major contributor to High Test Maintenance Cost because they take longer to understand each time they are visited. When they need to be modified, they take more effort to adjust and are much less likely to "work the first time," resulting in more debugging of tests. Obscure Tests are also more likely to end up not catching conditions they were intended to detect, which can lead to Buggy Tests (page 260 ).

Obscure Tests are best addressed by refactoring tests to focus on the reader of the tests. The real goal is Tests as Documentation (see page 23 )—anything less will increase the likelihood of High Test Maintenance Cost .

Cause: Hard-to-Test Code

"Legacy software" (i.e., any software that doesn't have a complete suite of automated tests) can be hard to test because we typically write the tests "last" (after the software already exists). If the design of the software is not conducive to automated testing, we may be forced to use Indirect Testing (see Obscure Test ) via awkward interfaces that involve a lot of accidental complexity; that effort may result in Fragile Tests .

It will take both time and effort to refactor the code to improve its testability. Nevertheless, that time and effort are well spent if they eliminate the High Test Maintenance Cost . If refactoring is not an option, we may be able to reduce the amount of test code affected by a change by doing SUT API Encapsulation (see Test Utility Method on page 599 ) using Test Utility Methods . For example, Creation Methods (page 415 ) encapsulate the constructors, thereby rendering the tests less susceptible to changes in constructor signatures or semantics.

Troubleshooting Advice

As a project-level smell, High Test Maintenance Cost is as likely to be detected by a project manager, scrum master, or team leader as by a developer. While managers may not have the technical depth needed to troubleshoot and fix the problem, the fact that they become aware of it is what is important. This awareness allows the manager to question the development team about how long it is taking to maintain tests, how often test maintenance occurs, and why it is necessary. Then the manager can challenge the developers to find a better way—one that won't result in such High Test Maintenance Costs !

Of course, the developers will need the manager's support to carry out whatever improvement plan they come up with. That support must include time to conduct the investigations ( spikes ), learning/training time, and time to do the actual work. Managers can make time for this activity by having "test refactoring stories," adjusting the velocity to reduce the new functionality committed to the customer, or other means. Regardless of how managers carve out this time, they must remember that if they don't give the development team the resources needed to fix the problem now, the problem will simply get worse and become even more challenging to fix in the future when the team has twice as many tests.

Production Bugs

We find too many bugs during formal tests or in production.

Symptoms

We have put a lot of effort into writing automated tests, yet the number of bugs showing up in formal (i.e., system) testing or production remains too high.

Impact

It takes longer to troubleshoot and fix bugs found in formal testing than those found in development, and even longer to troubleshoot and fix bugs found in production. We may be forced to delay shipping the product or putting the application into production to allow time for the bug fixes and retesting. This time and effort translate directly into monetary costs and consume resources that might otherwise be used to add more functionality to the product or to build other products. The delay may also damage the organization's credibility in the eyes of its customers. Poor quality has an indirect cost as well, in that it lowers the value of the product or service we are supplying.

Causes

Bugs may slip through to production for several reasons, including Infrequently Run Tests or Untested Code . The latter problem may result from Missing Unit Tests or Lost Tests .

By specifying that "enough tests" be run, we mean the test coverage should be adequate, rather than that some specific number of tests must be carried out. Changes to Untested Code are more likely to result in Production Bugs because there are no automated tests to tell the developers when they have introduced problems. Untested Requirements aren't being verified every time the tests are run, so we don't know for sure what is working. Both of these problems are related to Developers Not Writing Tests (page 263 ).

Cause: Infrequently Run Tests
Symptoms

We hear that our developers aren't running the tests very often. When we ask some questions, we discover that running the tests takes too long ( Slow Tests ; see page 253 ) or produces too many extraneous failures ( Buggy Tests ; see page 260 ).

We see test failures in the daily Integration Build [SCM]. When we dig deeper, we find that developers often commit their code without running the tests on their own machines.

Root Cause

Once they've seen the benefits of working with the safety net of automated tests, most developers will continue using these tests unless something gets in the way. The most common impediments are Slow Tests that slow down the pre-integration regression testing or Unrepeatable Tests (see Erratic Test on page 228 ) that force developers to restart their test environment or do Manual Intervention (page 250 ) before running the tests.

Possible Solution

If the root cause is Unrepeatable Tests, we can try switching to a Fresh Fixture (page 311 ) strategy to make the tests more deterministic. If the cause is Slow Tests, we must put more effort into speeding up the test run.

Cause: Lost Test
Symptoms

The number of tests being executed in a test suite has declined (or has not increased as much as expected). We may notice this directly if we are paying attention to test counts. Alternatively, we may find a bug that should have been caused by a test that we know exists but, upon poking around, we discover that the test has been disabled.

Root Cause

Lost Tests can be caused by either a Test Method (page 348 ) or a Testcase Class (page 373 ) that has been disabled or has never been added to the AllTests Suite (see Named Test Suite on page 592 ).

Tests can be accidentally left out (i.e., never run) of test suite in the following circumstances:

  • We forget to add the [test] attribute to the Test Method, or we accidentally use a method name that doesn't match the naming convention used by the Test Discovery (page 393 ) mechanism.
  • We forget to add a call to suite.addTest to add the Test Method to the Test Suite Object (page 387 ) when we are automating tests in a Test Automation Framework (page 298 ) that supports only Test Enumeration (page 399 ).
  • We forget to add a call to the Test Method explicitly in the Test Suite Procedure (see Test Suite Object ) in procedural-language variations of xUnit.
  • We forget to add the test suite to the Suite of Suites (see Test Suite Object ) or forget to add the [Test  Fixture] attribute to the Testcase Class .

Tests that ran in the past may have been disabled in any of the following ways:

  • We renamed the Test Method to not match the pattern that causes Test Discovery to include the test in the test suite (e.g., the method name starts with "test . . .").
  • We added an [Ignore] attribute in variants of xUnit that use method attributes to indicate Test Methods .
  • We commented out (or deleted) the code that adds the test (or suite) to the suite explicitly.

Typically, a Lost Test occurs when a test is failing and someone disables it to avoid having to wade through the failing tests when running other tests. It may also occur accidentally, of course.

Possible Solution

There are a number of ways to avoid introducing Lost Tests .

We can use a Single Test Suite (see Named Test Suite ) to run a single Test Method instead of disabling the failing or slow test. We can use the Test Tree Explorer (see Test Runner on page 377 ) to drill down and run a single test from within a test suite. Both of these techniques are made difficult by Chained Tests (page 454 )—a deliberate form of Interacting Tests (see Erratic Test )—so this is just one more reason to avoid them.

If our variant of xUnit supports it, we can use the provided mechanism to ignore 1 a test. It will typically remind us of the number of tests not being run so we don't forget to re-enable them. We can also configure our continuous integration tool to fail the build if the number of tests "ignored" exceeds a certain threshold.

We can compare the number of tests we have after check-in with the number of tests that existed in the code branch immediately before we started integration. We simply verify that this count has increased by the number of tests we have added.

We can implement or take advantage of Test Discovery if our programming language supports reflection.

We can use a different strategy for finding the tests to run in the Integration Build. Some build tools (such as Ant) let us find all files that match a name pattern (e.g., those ending in "Test"). We won't lose entire test suites if we use this capability to pick up all the tests.

Cause: Missing Unit Test
Symptoms

All the unit tests pass but a customer test continues to fail. At some point, the customer test passed—but no unit tests were written to verify the behavior of the individual classes. Then, a subsequent code change modified the behavior of one of the classes, which broke its functionality.

Root Cause

Missing Unit Tests often happen when a team focuses on writing the customer tests but fails to do test-driven development using unit tests. The team members may have built enough functionality to pass the customer tests, but a subsequent refactoring broke it. Unit tests would likely have prevented the code change from reaching the Integration Build.

Missing Unit Tests can also arise during test-driven development when developers get ahead of themselves and write some code without having a failing test to guide them.

Possible Solution

The trite answer is to write more unit tests. Of course, this is easier said than done, and it isn't always effective. Doing true test-driven development is the best way to avoid having Missing Unit Tests without writing unnecessary tests merely to get the test count up.

Cause: Untested Code
Symptoms

We may just "know" that some piece of code in the SUT is not being exercised by any tests. Perhaps we have never seen that code execute, or perhaps we used code coverage tools to prove this fact beyond a doubt. In the following example, how can we test that when timeProvider throws an exception, this exception is handled correctly?

public  String  getCurrentTimeAsHtmlFragment()
        throws  TimeProviderEx  {
     Calendar  currentTime;
     try  {
         currentTime  =  getTimeProvider().getTime();
     }  catch  (Exception  e)  {
         return  e.getMessage();
     }
     //  etc.

Root Cause

The most common cause of Untested Code is that the SUT includes code paths that react to particular ways that a depended-on component (DOC) behaves and we haven't found a way to exercise those paths. Typically, the DOC is being called synchronously and either returns certain values or throws exceptions. During normal testing, only a subset of the possible equivalence classes of indirect inputs are actually encountered.

Another common cause of Untested Code is incompleteness of the test suite caused by incomplete characterization of the functionality exposed via the SUT's interface.

Possible Solution

If the Untested Code is caused by an inability to control the indirect inputs of the SUT, the most common solution is to use a Test Stub (page 529 ) to feed the various kinds of indirect inputs into the SUT to cover all the code paths. Otherwise, it may be sufficient to configure the DOC to cause it to return the various indirect inputs required to fully test the SUT.

Cause: Untested Requirement
Symptoms

We may just "know" that some piece of functionality is not being tested. Alternatively, we may be trying to test a piece of software but cannot see any visible functionality that can be tested via the public interface of the software. All the tests we have written pass, however.

When doing test-driven development, we know we need to add some code to handle a requirement. However, we cannot find a way to express the need for code to log the action in a Fully Automated Test (see page 26 ) such as this:

public  void  testRemoveFlight()  throws  Exception  {
      //  set  up
      FlightDto  expectedFlightDto  =  createARegisteredFlight();
      FlightManagementFacade  facade  =
              new  FlightManagementFacadeImpl();
      //  exercise
      facade.removeFlight(expectedFlightDto.getFlightNumber());
      //  verify
      assertFalse("flight  should  not  exist  after  being  removed",
                      facade.flightExists(  expectedFlightDto.
                                                                getFlightNumber()));
}

Note that this test does not verify that the correct logging action has been done. It will pass regardless of whether the logging was implemented correctly—or even at all. Here's the code that this test is verifying, complete with the indirect output of the SUT that has not been implemented correctly:

public  void  removeFlight(BigDecimal  flightNumber)
              throws  FlightBookingException  {
      System.out.println("          removeFlight("+flightNumber+")");
      dataAccess.removeFlight(flightNumber);
      logMessage("CreateFlight",  flightNumber);  //  Bug!
}

If we plan to depend on the information captured by logMessage when maintaining the application in production, how can we ensure that it is correct? Clearly, it is desirable to have automated tests verify this functionality.

Impact

Part of the required behavior of the SUT could be accidentally disabled without causing any tests to fail. Buggy software could be delivered to the customer. The fear of introducing bugs could discourage ruthless refactoring or deletion of code suspected to be unneeded (i.e., dead code).

Root Cause

The most common cause of Untested Requirements is that the SUT includes behavior that is not visible through its public interface. It may have expected "side effects" that cannot be observed directly by the test (such as writing out a file or record or calling a method on another object or component)—in other words, it may have indirect outputs.

When the SUT is an entire application, the Untested Requirement may be a result of not having a full suite of customer tests that verify all aspects of the visible behavior of the SUT.

Possible Solution

If the problem is missing customer tests, we need to write at least enough customer tests to ensure that all components are integrated properly. This may require improving the design-for-testability of the application by separating the presentation layer from the business logic layer.

When we have indirect outputs that we need to verify, we can do Behavior Verification (page 468 ) through the use of Mock Objects (page 544 ). Testing of indirect outputs is covered in Chapter 11 , Using Test Doubles .

Cause: Neverfail Test
Symptoms

We may just "know" that some piece of functionality is not working, even though the tests for that functionality pass. When doing test-driven development, we have added a test for functionality we have not yet written but we cannot get the test to fail.

Impact

If a test won't fail even when the code to implement the functionality doesn't exist, how useful is it for Defect Localization (see page 22 )? Not very!

Root Cause

This problem can be caused by improperly coded assertions such as assertTrue(aVariable,  true ) instead of assertEquals(aVariable,  true ) or just assertTrue(aVariable) . Another cause is more sinister: When we have asynchronous tests, failures thrown in the other thread or process may not be seen or reported by the Test Runner .

Possible Solution

We can implement cross-thread failure detection mechanisms to ensure that asynchronous tests do, indeed, fail. An even better solution is to refactor the code to support a Humble Executable (see Humble Object on page 695 ).