Skip to content
Advertisement

Having problems trying to test functionality that contains autowired SprngBoot with junit 5

I want to test some functinality, a service with a repo that is autowired in. I dont want to mock the autowired, this is more a integration test for debugging.

My test is as follow

JavaScript

The code is very simple

JavaScript

The problem is that throttleRateRepository is always null.

I have managed to test this sort of code before. With Junit 4 with

JavaScript

Which autowired all the beans. Its been a while since I did this sort of integration testing, and its all changed with Junit 5. Thanks or any hep.

Advertisement

Answer

The issue in that code:

JavaScript

You shouldn’t create beans manually. In this case Spring cannot manage it and autowire repository.

If you need to recreate your service before each method call, you can use class annotation @DirtiesContext(methodMode = MethodMode.AFTER_METHOD). You can read about it more here.

Instead of this, autowire ThrottleRateServiceImpl like the repository. Also, for the correct autowiring, you may need to have a test configuration. It could be inner static class, or a separate class.

JavaScript

You can read more about initializing beans for testing and test configurations in this tutorial.

Also, very helpful an official documentation:

If you are using JUnit 4, do not forget to also add @RunWith(SpringRunner.class) to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there is no need to add the equivalent @ExtendWith(SpringExtension.class) as @SpringBootTest and the other @…​Test annotations are already annotated with it.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement