自动装配的 TestEntityManager 在 TestEntityManager 对象上有空指针
Autowired TestEntityManager Has Null Pointer on TestEntityManager Object
我想使用 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);
}
我有一个Spring应用程序主文件,但没有控制器。
这是我的测试文件。我也试过@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());
}
}
您不能在静态字段上使用@Autowired。
重构您的测试以改用实例字段。
请记住:
- Junit 在每次测试前创建一个新的测试实例 class
- 默认情况下,用@DataJpaTest 注释的测试是事务性的,并在每个测试结束时回滚。
Can you use @Autowired with static fields?
我想使用 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);
}
我有一个Spring应用程序主文件,但没有控制器。
这是我的测试文件。我也试过@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());
}
}
您不能在静态字段上使用@Autowired。 重构您的测试以改用实例字段。 请记住:
- Junit 在每次测试前创建一个新的测试实例 class
- 默认情况下,用@DataJpaTest 注释的测试是事务性的,并在每个测试结束时回滚。
Can you use @Autowired with static fields?