【发布时间】: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