December 2024
Intermediate
5 pages
2m
English
Refactoring unit tests is not just about making tests pass but about improving their structure, readability, and maintainability. Let’s look at a couple best practices when refactoring tests.
You should address testing code in the same way you apply these shortcuts to production code. Clean code is about simplicity and short sentences. You can refactor long tests with the same tools.
Here’s a long test in JavaScript addressing two different issues (see “Write Good Test Assertions” in this Shortcut series):
test('User can log in and see dashboard',()=>{constuser=newUser('Esther Piscore');user.login('password123');expect(user.isLoggedIn()).toBe(true);constdashboard=user.getDashboard();expect(dashboard).toContain('Welcome, Esther Piscore');});
You can refactor it in two different tests:
test('User can log in with correct credentials',()=>{constuser=newUser('Esther Piscore');user.login('password123');expect(user.isLoggedIn()).toBe(true);});test('User sees welcome message on dashboard',()=>{constuser=newUser('Esther Piscore');user.login('password123');constdashboard=user.getDashboard();expect(dashboard).toContain('Welcome, Esther Piscore');});
You can also extract a common protocol like this setup in Java:
@TestvoidtestUserLogin(){Useruser=newUser("Esther Piscore","password123");user.login();assertTrue(user.isLoggedIn ...
Read now
Unlock full access