Repository autowiring fails during Spring Data JPA Test with Testcontainers, NullPointerException is thrown

33 Views Asked by At

Spring fails to autowire my repository that I want to inject to the test using DataJpaTest annotation. Here is the code of my test:

package org.mwdziak.vaccinationbackend.repository;

import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.mwdziak.vaccinationbackend.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import java.time.LocalDate;


@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class UserRepositoryTests {

    @Autowired
    private UserRepository userRepository;

    @Container
    static MySQLContainer mySQLContainer = new MySQLContainer("mysql:8.0.26")
            .withDatabaseName("vaccination")
            .withUsername("vaccination")
            .withPassword("vaccination");

    @DynamicPropertySource
    static void mySqlProperties(org.springframework.core.env.ConfigurableEnvironment environment) {
        environment.getSystemProperties().put("spring.datasource.url", mySQLContainer.getJdbcUrl());
        environment.getSystemProperties().put("spring.datasource.username", mySQLContainer.getUsername());
        environment.getSystemProperties().put("spring.datasource.password", mySQLContainer.getPassword());
    }

    @Test
    public void should_save_user() {
        //Arrange
        var user = User.builder()
                .password("test")
                .email("test")
                .firstName("test")
                .lastName("test")
                .dateOfBirth(LocalDate.now())
                .role(User.Role.USER)
                .build();

        //Act
        var saved = userRepository.save(user);
        //Assert
        Assertions.assertNotNull(saved);
    }
}

Here is the code of my repository:

package org.mwdziak.vaccinationbackend.repository;

import org.mwdziak.vaccinationbackend.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

And here are the logs:

java.lang.NullPointerException: Cannot invoke "org.mwdziak.vaccinationbackend.repository.UserRepository.save(Object)" because "this.userRepository" is null

    at org.mwdziak.vaccinationbackend.repository.UserRepositoryTests.should_save_user(UserRepositoryTests.java:51)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)

I tried testing whether other of my repositories will be injected, but the same problem occurs, adding a @SpringBootTest annotation doesn't help either.

1

There are 1 best solutions below

0
Panagiotis Bougioukos On

As can be seen from your logs you have used junit4

at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)

In that case you miss another required annotation -> @RunWith(SpringRunner.class) in your test class, which is the reason your test class is not correctly set up.

This is also described in the documentation of @DataJpaTest.

When using JUnit 4, this annotation should be used in combination with @RunWith(SpringRunner.class).