【问题标题】:Autowired TestEntityManager Has Null Pointer on TestEntityManager Object自动装配的 TestEntityManager 在 TestEntityManager 对象上有空指针
【发布时间】:2020-01-30 01:16:44
【问题描述】:

我想使用 Spring Data REST 和 Spring Data JPA 测试 Spring Boot 应用程序。但是,测试文件中的 TestEntityManager 对象不会自动装配,因此为空。我在网上搜索并没有发现我在单元测试文件中做错了什么。有人可以帮忙吗?

实体 -- 学生:

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

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

    .....// other fields
   }

还有学生存储库:

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

我有一个 SpringApplication 主文件,但没有控制器。

这是我的测试文件。我也尝试了@SpringBootTest 和@AutoConfigureTestEntityManager,但entityManager 仍然为空。

@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());       
   }
}

【问题讨论】:

    标签: spring-boot jpa spring-data-jpa spring-data-rest


    【解决方案1】:

    您不能在静态字段上使用@Autowired。 重构您的测试以改用实例字段。 请记住:

    • Junit 在每次测试之前创建一个新的测试类实例
    • 默认情况下,使用@DataJpaTest 注释的测试是事务性的,并在每个测试结束时回滚。

    Can you use @Autowired with static fields?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-26
      • 2016-11-11
      • 1970-01-01
      • 2017-12-27
      • 2012-05-23
      • 2017-08-04
      • 2017-11-20
      • 2014-11-17
      相关资源
      最近更新 更多