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

@SpringBootConfiguration
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ThrottleRateServiceTest {
    
    ThrottleRateService service = null;
    
    @BeforeEach
    public void setUp() {
        service = new ThrottleRateServiceImpl();
    }
    
    @Test
    public void testThrottoling() {
        service.isAllowed("test");
    }
}

The code is very simple

@Service
public class ThrottleRateServiceImpl implements ThrottleRateService {
    
    private final Logger logger = LogManager.getLogger(ThrottleRateServiceImpl.class);
    
    @Autowired
    ThrottleRateRepository throttleRateRepository;

The problem is that throttleRateRepository is always null.

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

@RunWith(SpringJUnit4ClassRunner.class) 

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:

@BeforeEach
public void setUp() {
    service = new ThrottleRateServiceImpl();
}

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.

@SpringBootConfiguration
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ThrottleRateServiceTest {

    @TestConfiguration
    static class TestConfig {
        @Bean
        public ThrottleRateService throttleRateService() {
            return new ThrottleRateServiceImpl();
        }
    }

    @Autowired
    ThrottleRateService service;

    @Test
    public void testThrottoling() {
        service.isAllowed("test");
    }
}

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