Doing unit testing for the first time at a large scale, I find myself writing a lot of repetitive unit tests for my business logic. Sure, to create complete test suites I need to test all possibilities but readability feels compromised doing what I do – as shown in the psuedocode below.
How would a well written, readable test suit look like?
describe "UserEntity" ->
it "valid name validates"
...
it "invalid name doesnt validate"
...
it "valid list of followers validate"
..
4
In general, a well written test suite inevitably contains some repetition, as you are testing the same method over and over with different parameters and results. But if you have significant chunks of duplicate test code, you can improve it by refactoring. Extract repeated code parts into separate methods which you can then reuse.
For a more detailed treatment, check out Growing Object-Oriented Software Guided by Tests. It contains lots of tips and practical examples on how to make your test code more concise, fluent and readable.
I really do like the AAA pattern.
// Arrange
arrange needed mocks, stubs, parameters, whatever
// Act
test
// Assert
validate test
1
in my eyes a good test looks like:
/*
description of what is tested (include mentions of whether it's general case, edge case, exceptional case)
include references to any relevant bug reports
*/
void testSomthing(){
prepare mocked behavior (if any)
set the input for the method
set expected_output from the test
gotten_output=do call to tested method
assertEquals(gotten_output, expected_output);
}
repeat for each test
without the documentation you won’t know which of the 2 dozen tests on a method test what