Internal Structure of Test Methods

Introduction

NUnit testing is done within an NUnit test project that contains multiple files, each containing test methods. Each test method is, in essence, a test case. The structure of a test method is important so that the reader can separate the context of the test from the actual expected outcomes.

Number of assertions per test method

A test method should contain one assertion. This is because a test method is, in essence, a test case and should test a single behavior. However, in terms of the test case structure, it is perfectly valid that the tested feature requires more than one assertion. However, keep in mind that one assertion per test method should be the goal. If one assertion doesn’t encapsulate the behavior for a given test, we should add one or more assertions. Some general rules can be used to determine whether we have too many assertions per test method.

It is commonly accepted that if a test method contains more than five assertions, it is most probably a code smell. This would mean that the test case is too broad and encompassing to be specific enough to test a single behavior. If we combine these rules and practices, we may derive the following best practice for test cases:

A test case should test a single expected outcome, result, feature, or specification. A test case should strive to contain a single assertion. If a single assertion does not cover the intended behavior of the application code, more assertions may be added. However, no more than five assertions should be used.

In the example below, we test whether a GetStoredValue method within the MyClass class returns values as expected. The expected behavior of this method is to always return a value between 100 and 200.

Get hands-on with 1400+ tech skills courses.