Search code examples
javaunit-testingtest-coverage

Does it make sense to write addition test for a method if it is already covered by another test?


I am testing my spring boot application with unit tests and in coverage report, I have +85% branch coverage. There are some cases where some methods are covered while testing other methods such as mappers, utility methods, etc.

For example, in the service method, I called mapper and utility methods, and those methods are marked as covered in the coverage report because I tested that service method.

My question is, does it make sense to write additional tests for those mapper and utility methods since they are already covered in the service tests?


Solution

  • I usually take a different approach that I would like to share.

    Say, I'm a developer that has got the task to create a Mapper or utility. At this time the Service doesn't even exist.

    I write my code, but then I want to check myself. So I unit test it. I don't care about the coverage at this point, for me, coverage is a tool that helps me to understand and decide whether I've made all the checks I need or I've missed an area in a code of Mapper that I wrote that possibly has a bug.

    So I've made sure that my code is perfect and I submit it and move to another task...

    Later (weeks, months, years) someone, me or another programmer, creates a Service that uses my code. Lets pretends its you, for example.

    So you basically don't care about Mapping code, you assume that it works. However you do want to check your Service, and so you write your unit tests that can mock the dependency on Mapper or run it within the test if its not a real dependency and its fast and everything. Again you don't care about the overall coverage, you care about your code, you want to make sure that your code doesn't have bugs, and again, coverage helps you make sure that you've done your best to check your code before it meets production.

    As for my old tests of Mapper - well, they're still run.

    Bottom line I don't think that code should be covered for the sake of coverage, but tests (and coverage) should provide you a safety net if you wish.

    With this in mind, You should write tests for your code, if you can mock other dependencies be it, if not - just run them.

    P.S. I believe there might be many different opinions of this, so there is no one single right answer for this question