Is it OK to use SpringRunner in unit tests?

故事扮演 提交于 2019-12-04 17:41:30

I tend to agree with your colleagues.

Unit tests should only test small units of code, typically a single class. They should exercise only the unit under test without executing any code from dependencies of the unit.

One reason for this is that unit tests should execute as fast as possible. In Test Driven Development (TDD), you want to be able to run the suite, or a at least a relevant subset of it, very often, after every small change you make, to verify that you didn't break any existing behavior. This is only feasible if the feedback from the tests is instantaneous. If you have to wait for the test results too long, you'll run them less often, which means the feedback loop gets longer.

In smaller Spring projects the Spring context loads quiet fast, so you might think there's not that much of a difference, but if you run the tests very often, even a short delay adds up. In large and older code bases it can take a while to ramp up the Spring context, and at some point it gets so slow that you don't want to run the whole test suite more than once a day, which considerably harms your ability to practice TDD.

Another dimension of sticking to testing small units of code is that it forces you to structure your code into highly decoupled (i. e. testable) units. If you can't write unit tests for a class that exercises only that class and nothing else, it's probably a hint that there's an opportunity to improve the design of the code.

To summarize, when you ramp up the whole Spring context for a test, by this definition, it is not a unit test anymore, but an integration test, because you are also testing the whole Spring configuration, bootstrapping, autowiring etc, i. e. the integration of your classes into a Spring application.

@SpringRunner should be used if you class is using any bean dependencies, if you class is independent one, without any application context dependencies, better not to use @SpringRunner. If i see you class 'RewardDurationCalculator' it doesn't use any dependencies, it should not use @SpringRunner and even for matter of fact Mocks...

For further reading:

  1. https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/junit4/SpringRunner.html
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!