Clean Testing Part II – Give a context for ‘arrange ‘ part

I have seen many times that unit tests were hard to read and maintain. I have seen tests in which the preparation of the test did not fit on the monitor. The different parts of the test were mixed and darkened. Units tests have to be clear and easy to maintain to give us value.

Good programmers write code that humans can understand – M. Fowler (1999)

I think this quote tells us that we should focus on naming things, contiouns refactoring and create class that have single resposibility

I would like to show you few advice how to write clean tests.

Let’s go to example

Some not good written implementation to make our example more real.

Legacy implementation Our goal is to make sure when user password is expired we will generate reset password token.

Bad Test

Bad Test

We have many mocks setups. In this the arragment part of the test is huge. At first glance, it’s hard to locate the method that we are testing. We have some hard coded test data. The date is format is not close to real. This code is not easy to read for a human to understand what we are testing and how we are testing.

Lets fix it.

The first thing we’ll do in our refactoring is getting rid of creating objects for testing in a non-elegant way. We will get rid of magic strings. We can extract the creation of objects like SignInCommand or UserAccount to static classes with a factory method. Test data to create these objects, we can use the Faker.NET library which gives the possibility to interfere with fake mail, phone number, first name etc.

Snap (1)

Like we can see. We have used Faker.NET to generate fake email and first name. Generated that is closer to real comparing to some ‘testtest’ phrases.

Now we have to only use our factory methods in our test.

Implemented avoid magic strings

Once we don’t have magic string in our tests we can start working on crucial part that makes this test hard to understand.

Mock setup refactor

To setup mock we use libary SDK. Mock setup in that way not give us author and we don’t know exactly which case is mocked on first glance. How to give code piece context? Name it better using private methods.

Even this method will have one line of code, this is no problem, beacuse context is a king.

Screen Shot 2022-09-09 at 8.15.38 PM
Screen Shot 2022-09-09 at 8.16.08 PM

Leave a Reply

Your email address will not be published. Required fields are marked *