0
votes

I want to test a Spring Boot application using Spring Data REST and Spring Data JPA. However the TestEntityManager object in the test file doesn't get autowired and thus is null. I googled online and didn't find out what I have done wrong in the unit test file. Can someone please help?

Entity -- Student:

@Data
@Entity
@Table(name = "STUDENT")
public class Student {

    @Column(name = "STUDENT_ID")
    private Integer id; 

    .....// other fields
   }

And the Student repository:

public interface StudentRepository extends CrudRepository<Student , Integer>{
  Student findById(@Param("id") int id);
}

And I have a SpringApplication main file, but no controller.

And here is my test file. I also tried with @SpringBootTest and @AutoConfigureTestEntityManager, but the entityManager is still null.

@RunWith(SpringRunner.class)
@DataJpaTest
public class StudentRepositoryTest {

    @Autowired
    private static TestEntityManager entityManager;  // entityManager is always Null 

    @Autowired
    private static StudentRepository repository; 

    private static Student student;

    @BeforeClass
    public static void setUp() throws Exception {

        entityManager.persistAndFlush(new Student("1"));  
          // Null Pointer exception because entityManager is null.
    }

    @Test
    public void testFindById() {        
        assertNotNull(repository.findById());       
   }
}
1

1 Answers

1
votes

You cannot use @Autowired on static fields. Refactor your test to use instance fields instead. Remember that:

  • Junit creates a fresh instance of test class before each test
  • By default, tests annotated with @DataJpaTest are transactional and roll back at the end of each test.

Can you use @Autowired with static fields?