Home > Enterprise >  @Autowired field is null although annotations are present
@Autowired field is null although annotations are present

Time:11-04

I am trying to write a dummy integration test to get some practice with these technologies that I am using for the first time, however I am currently facing an NullPointerException on my autowired repository field (called movieRepository).

I saw from other questions that the main cause was not setting annotations correctly. However, I don't think this is the case since MovieRepository doesn't have the @Repository annotation because MongoRepository as I understand it doesn't require it (but even adding it doesn't change anything) and instead MovieRepositoryIntegrationTest inherits the annotation from the abstract class it extends.

MovieRepository.java

package com.example.testingtwo.repository; // /main/
public interface MovieRepository extends MongoRepository<Movie, String> {

}

AbstractContainerBaseTest.java

package com.example.testingtwo; // /test/
@DataMongoTest
public abstract class AbstractContainerBaseTest {

    static final MongoDBContainer mongoDBContainer;

    static {
        mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:6.0.2"));
        mongoDBContainer.start();
    }

    @DynamicPropertySource
    static void setProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl);
    }
}

MovieRepositoryIntegrationTest.java

package com.example.testingtwo.repository; // /test/
public class MovieRepositoryIntegrationTest extends AbstractContainerBaseTest {

    @Autowired
    private MovieRepository movieRepository;

    @AfterEach
    void cleanUp() {
        movieRepository.deleteAll();
    }

    @Test
    public void testFindById() {
        Movie movie = new Movie(null, "Test Name", "Test Description");
        String movieId = movieRepository.save(movie).getId(); // java.lang.NullPointerException: "this.movieRepository" is null
        Movie movieFound = movieRepository.findById(movieId).orElse(null);

        assertNotNull(movieFound);
        assertEquals(movieFound.getName(), movie.getName());
        assertEquals(movieFound.getDescription(), movie.getDescription());
    }
}

Other information:

  • Java 17
  • Spring Boot 3.0 RC1
  • Junit5
  • Build tool: Maven
  • Spring Dependencies: Spring Web, Spring Data MongoDB, Lombok, Testcontainers

CodePudding user response:

The fact that a dependency is null tells me that likely the unit test is not running in the Spring context and so it is as if you didn't even have the @Autowired annotation. Are you using junit4? According to the javadoc for @DataMongoTest "When using JUnit 4, this annotation should be used in combination with @RunWith(SpringRunner.class)."

  • Related