Member-only story
13 Tips for Writing Useful Unit Tests
How you write your tests is as important as writing them

In my previous article, I made the case that you should be unit testing your code. I think I made the case pretty well.
In this article, I’ll cover some tips and pointers about how to unit test your code. Here we go.
1. Test One Thing at a Time in Isolation
This is probably the baseline rule to follow when it comes to unit tests. All classes should be tested in isolation. They should not depend on anything other than mocks and stubs.
They shouldn’t depend on the results of other tests. They should be able to run on any machine. You should be able to take your unit test executable and run it on your mother’s computer when it isn’t even connected to the internet.
2. Follow the AAA Rule: Arrange, Act, Assert
When it comes to unit testing, AAA stands for Arrange, Act, Assert. It is a general pattern for writing individual tests to make them more readable and useful.
First, you arrange. In this step, you set things up to be tested. You set variables, fields, and properties to enable the test to be run, as well as define the expected result.
Then you act — that is, you call the method that you are testing.
Finally, you assert— call the testing framework to verify that the result of your “Act” is what was expected. Follow the AAA principle, and your test will be clear and easy to read.
3. Write Simple “Fastball-Down-the-Middle” Tests First
The first tests you write should be the simplest — the happy path. They should be the ones that easily and quickly illustrate the functionality you are trying to write.
If you are writing an addition algorithm, the early tests that you write should make sure that your code can do 2 + 2 = 4. Then, once those tests pass, you should start writing the more complicated tests (as discussed below) that test the edges and boundaries of your code.