Positive vs Negative Tests
Learn how writing negative tests may enhance unit test coverage.
Introduction
A natural inclination when writing test cases is to check that a test case behaves as expected with expected input. This is only one side of the coin when writing a test case. To write a test case that comprehensively checks the behavior of a method, we need to check that a method behaves as expected with unexpected input. A positive case tests whether the code behaves like it should. A negative case tests whether the code does not behave like it shouldn’t. These two terms are very difficult to define and are best demonstrated by example.
Differences between positive and negative tests
The best way to demonstrate this concept is to use an example of a human resources department approving leave applications. Suppose that only the human resource manager may approve leave applications. The positive test would assert that a human resource manager can approve applications. Note how the positive test statement mimics the behavior that is expected. This is why we mentioned in the introduction that it is a natural inclination to formulate a positive test. A negative test in this example would assert that all other roles in the human resources department cannot approve leave requests.
Positive and negative tests should therefore be used together to ensure that the application code behaves as expected.
When to formulate positive and negative tests
Since test cases are almost always formulated in the positive, it is easy to think about and write positive tests. However, not all test cases have a practical value when tested for in the positive. For instance, suppose we have a
GetTriangleType
method that gets the triangle type.
Get hands-on with 1400+ tech skills courses.