Reflection in unit tests to verify code coverage

Here is the script. I have VO objects (Value objects) or DTOs that are only containers for data. When I take them and separate them for saving in a database, which (for many reasons) does not belong to VO elegantly, I want to check whether each field will be successfully created in the database and successfully read back to restore VO.

Is there a way to verify that my tests cover all fields in VO? I had the idea of โ€‹โ€‹using reflection to iterate over the VO fields as part of the solution, but maybe you guys solved the problem earlier?

I want this test to fail when I add fields to VO, and remember to add validations for it in my tests.

dev environment: Using JUnit, Hibernate / Spring, and Eclipse

+4
source share
3 answers

Keep it simple : write one test for VO / DTO:

  • fill VO / DTO with test data
  • save him
  • (optional: verify that everything was correctly stored at the database level using pure JDBC)
  • upload it
  • make sure the loaded VO / DTO and the original match

Production code will evolve and tests should also be kept. Conducting the simplest tests, even if they are repeated, is the best approach to IMHO. Over-engineering the tests or the test environment itself, to make the tests generalized (for example, by reading the reflection fields and filling in the VO / DTO automatically) leads to several problems:

  • the time taken to record the test is higher
  • an error can be introduced in the test itself
  • test maintenance is more difficult because it is more complex
  • harder to develop, for example. general code may not work for new VO / DTO types that are slightly different from each other and will be introduced later (this is just an example).
  • tests cannot be easily used as an example of how productive code works

Test and productive code are very different in nature . In productive code, you try to avoid duplication and maximize reuse. Productive code can be complicated because it is tested. On the other hand, you should try as simple tests as possible, and duplication is fine. If the duplicated part is broken, the test will still fail.

When changing a productive code, this may require several changes three times. The problem is that tests are seen as a boring piece of code. But I think it should be so.

If, however, I misunderstood your question, just let me know.

+5
source

I would recommend cobertura for this task. After running the tests, you will get a full report on the coverage of the code, and if you use the cobertura-check ant task, you can add checks for coverage and stop the ant call using the haltonfailure property.

+1
source

You can make this part of the VO test. If fields are not specified when using a getter, it may throw an exception.

0
source

Source: https://habr.com/ru/post/1310382/


All Articles