Architecture & DesignTop Five Best Practices for Writing Unit Test Scripts

Top Five Best Practices for Writing Unit Test Scripts content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


Unit testing is one of the steps in the software development process where every part or unit of code is verified to ensure it behaves as expected. When the code is modified in the future, the automated unit tests help ensure the existing functionality is intact. Unit tests can be done manually or coded. Unit tests are generally created by programmers.

In this article, we will discuss the best practices to be remembered and followed when writing unit tests.


There are a tools like re-sharper, NUnit, moles, and so forth that can be integrated with developer tools like Visual Studio to write and run unit tests. Let’s understand with the help of an example. Following is the code we want to write unit test scripts for. It’s a function that takes two input parameters. This method has two parts; L ine 5 validates if the value of ‘y’ > 0 and Line 8 returns the quotient when ‘x’ is divided by ‘y’.

 1. public class Class1
 2. {
 3.     public float Div(float x, float y)
 4.     {
 5.        if (y <= 0)
 6.           return -1;
 8.           return x / y;
 9.     }
 10. }

The test method for the preceding function is as follows:

 1. [TestClass()]
 2. public class Class1Tests
 3. {
 4.    [TestMethod()]
 5.    public void DivTest()
 6.    {
 7.       Class1 passScenario = new Class1();
 8.       var p = passScenario.Div((float)10,
 9.       Assert.AreEqual(p,5.0);
10.    }
12.    [TestMethod()]
13.    public void DivTestException()
14.    {
15.       Class1 excepScenario = new Class1();
16.       var p = excepScenario.Div((float)10,
17.       Assert.AreEqual(p, -1);
18.    }
19. }

The test class is prefixed with ‘[TestClass()]’ and the method is prefixed with ‘[TestMethod()]’. In this example, the ‘DivTest’ method only validates the positive scenario where the value of ‘y’ is greater than 0 and ‘DevTestException’ validates the exception scenario where ‘y’ is equal to 0. The code coverage for the previous method will be 100% as a positive scenario & the negative scenario both are covered. Ideal code coverage should be greater than 80%. Now, let’s examine the characteristics of good unit test cases.

Characteristics of Good Unit Tests

1. Isolated: Each Unit Test Should Be Able to Run Independently

Generally in a project, all the tests are run at one time. The order in which the tests are run cannot be determined; for this reason, the tests should be independent of each other. In the preceding example, either a positive scenario or the negative scenario can get executed first.

2. Test Only One Condition at a Time

There should only be one assert statement for each test method. In the preceding example, there are two test methods: one to verify the positive and one for the exception scenario. Now, when the tests are run, each scenario is validated separately. Explicit assertion for every method gives an instant insight of the failed tests and helps analyze the scripts easily.

3. Repeatable

The tests should return the same result whenever and how many times it’s executed. The result shouldn’t change from one execution to another.

4. Thorough

Thorough testing is related to how many units of code are verified. Code coverage gives a good indication of how much testable code is verified. A code coverage of 80% and above is a good indication that most of the code is covered by unit test scripts.

5. Mock External References

Mock external references, the test script, when run should not depend on external entities such as connection to a database or WCF or a configuration file. Mocking external references essentially means that it’s assumed that the expected data is returned from the source and the testable code only verifies the actions that are performed on that data.

Another reason for mocking is if there is a connection problem with the external entity, the unit test scripts are bound to fail; there are two levels of testing being done, one for the external entity and other of the action performed on the data retrieved. Ideally, these should be two different test scripts to identify the bug better. Unit tests are not meant for integration test.

The unit test scripts are generally run as a part of continuous integration (CI) where the build is fired and, after the build is generated, the unit test scripts are run against the assemblies.


In the preceding sections, we discussed the characteristics of unit tests; however, unit tests are not for finding bugs or regression tests because only a unit of code is verified and not the functionality of the application when all the code is integrated. Writing unit tests also requires time because unit test scripts are also code that are used to verify the smallest testable unit of code. Unit tests helps reduce time in the future when further changes are done to the application; however, automating unit tests for complete code may be a time-consuming process and not be worth the time and effort. Therefore, it’s important to strike a balance between automation and manual testing.


Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories