Over the years, I’ve observed developers applying dozens of anti-patterns to testing.
The result: An expensive test suite that is not fun to work with.
Here is one of these test anti-patterns:
🛑 Test Anti-pattern 🛑
Copy-pasting real data as test data
Tests often contain test data that is unnecessarily complex or elaborate.
❌ avoid:
it('loads user plan', async () => {
fetch.mockResolvedValue({
id: '603064',
firstname: 'Alysa',
lastname: 'Patton',
email: 'apatton0@myspace.com',
bio: 'I am a software developer with advanced testing skills. I hate writing tests first. But my code coverage is usually around 70%.',
followers: 20,
following: 3,
plan: {
name: 'Medium',
quota: 1000,
},
})
expect(await loadPlanForUser('603064')).toEqual('Medium')
})
Most of the above test data is not required to prove that the tested code does what it is supposed to do.
âś… prefer:
it('loads user plan', async () => {
fetch.mockResolvedValue({ id: '1', plan: { name: 'Medium' } })
expect(await loadPlanForUser('1')).toEqual('Medium')
})
Using actual test data in tests creates several problems:
Tests with real data are hard to understand
Tests that use real data will likely take more time to understand. When reading the test, we must assume that the data is essential. But all this unnecessary data distracts from what the test is actually trying to accomplish.
Tests with real data drag development speed down
Using actual data increases the test file size and, thus, the cognitive load required to comprehend the code. Having to weed through test code, as the one in the negative example above, will tire developers faster and drag the overall development speed down.
Tests with real data are more expensive to maintain
The larger the average file size, the more expensive it will be to maintain the project. Everything takes longer: Scrolling, reading, trying to make sense of the test code. It might only be a second here or there, but the lost performance accumulates quickly to several developer weeks per year.
Tests with real data discourage refactoring
A test with real data suggests that the data is important. Other developers will likely not question that. The problem is that the increased complexity discourages refactoring. The result: The code base deteriorates further.
Tests with real data potentially leak sensitive data
And last but not least, copy-pasting actual data into test files might accidentally expose sensitive data such as personally identifiable information (PII) or secrets.
So, don’t copy-paste real data as test data!
See you around,
-David