Reputation: 172
I have one question related to the test data and the test-class structure. I have a test class with few tests inside. Now, the given and the expected data are structures that I create for almost every test. I write my tests to look like this:
private static final List<String> EXPECTED_DATA = List.of("a","b","c","d","e","f");
@Test
void shouldReturnAttributes() {
Service service = new Service();
List<String> actualData = service.doSomething();
assertThat(actualData).containsExactlyInAnyOrderElementsOf(TestData.EXPECTED_DATA);
}
Currently, I set my test data at the beginning of the test class as constants. Once more tests are added, more constants start appearing at the beginning of the test class, resulting in a lot of scrolling down to reach the actual tests. So, a friend came up with an idea that if the constants are not on the top of the test class, the tests will be more readable. The test data that are used from more that one test class are moved to a CommonTestData class and the rest test data that are used only from a specific class we structured them as follows.
We moved them inside a private static class TestData and the code looks like this:
class ProductAttributeServiceTest {
@Test
void shouldReturnAttributes() {
Service service = new Service();
List<String> actualData = service.doSomething();
assertThat(actualData).containsExactlyInAnyOrderElementsOf(EXPECTED_DATA);
}
private static class TestData {
private static final List<String> EXPECTED_DATA = List.of("a","b","c","d","e","f");
}
}
Could you propose another way of doing that? How do you structure your test data to improve test readability?
Upvotes: 0
Views: 243
Reputation: 41
One approach could be put the test data in text,csv type files..
Putting the test data in file would give chance to name the files with specific test scenarios. Which will eventually add more readability to the test data. And these files can be arranged in test scenario based folder structures as well.
Once test data been arranged in files then the owner ship and maintenance of these files can be transferred to domain experts and test data can be added/ modified directly on need basis.
One test data supplier class can be created which will do task of reading the test data from the files and provide to test.
So tests would have communication only to this supplier class through an API like,
Public string getTestData(string test scenario name)
And if the test data on each constant is not that much big to put in separate files.. then a single json yml based config file having one field for each data constant would do the job.
Upvotes: 1