Java 不扩展任何Spring数据存储库的测试存储库
我正在为我的应用程序编写单元和集成测试,我在测试存储库方面遇到了问题 这对于经办机构来说是非常简单的回购:Java 不扩展任何Spring数据存储库的测试存储库,java,spring-boot,junit4,spring-repositories,Java,Spring Boot,Junit4,Spring Repositories,我正在为我的应用程序编写单元和集成测试,我在测试存储库方面遇到了问题 这对于经办机构来说是非常简单的回购: public interface AuthorityRepository { Authority saveAuthority (Authority authority); } 关于此代码,我有两个问题: 不扩展任何Spring数据存储库接口是错误的方法吗?除了不必编写所有与数据库通信的方法之外,使用它还有什么其他优点 如何使用最少的资源测试此存储库@DataJpaTest不起作
public interface AuthorityRepository {
Authority saveAuthority (Authority authority);
}
关于此代码,我有两个问题:
@DataJpaTest
不起作用,因为(据我所知)它接收扩展任何Spring数据存储库的repo。这项工作:@SpringBootTest
非常慢,因为它创建了整个应用程序上下文,我想让这些测试更快。
我在main和test中使用H2数据库,它在
应用程序.properties
文件中声明。@DataJpaTest
与@Import(repo.class)
结合使用时工作。看起来是这样的:
@RunWith(SpringRunner.class)
@DataJpaTest ()
@Import(AuthorityRepositoryImpl.class)
public class AuthorityRepositoryTest2 {
@Autowired
AuthorityRepository authorityRepository;
@Autowired
TestEntityManager testEntityManager;
@Test
public void test() {
Authority authority = new Authority();
authority.setUsername("name");
authority.setUsername("username");
authorityRepository.saveAuthority(authority);
assertNotNull(testEntityManager.find(Authority.class, 1));
}
不过,我了解到,如果我进行集成测试,我也可以创建整个应用程序上下文,并测试我希望重用的所有内容。因此,稍后,当我为我的应用程序的其他部分编写更多集成测试时,我将使用@springbootest
进行所有这些测试
感谢您的评论,帮助我更好地理解集成测试。1)这没有错,但我不明白您为什么不使用合适的存储库2)您不应该首先测试存储库,因为它不包含业务逻辑谢谢:)如果我有一些高级查询,我想检查它们是否返回正确的结果,并确保在我更改代码后仍然返回正确的结果,该怎么办?集成测试将是更好的地方。此外,代码更改通常不会中断查询。数据更改。您是否尝试过使用
DataJpaTest
?它应该可以工作,因为它将引导一个最小的测试,并配置JPA和可选的Spring数据JPA。类似于@DataJpaTest(AuthorityRepositoryImpl.class)
。应该是可能的。仅在集成测试中使用@springbootest
或@DataJpaTest
。集成测试很慢,应该与单元测试分开。与集成测试不同,单元测试应该经常运行。集成测试通常在pull-request/push-to-repo和CI管道上运行一次。
@RunWith(SpringRunner.class)
@SpringBootTest
public class AuthorityRepositoryTest {
@Autowired
private AuthorityRepository authorityRepository;
@PersistenceContext
private EntityManager entityManager;
@Test
public void test () {
Authority authority = new Authority();
authority.setName("name");
authority.setUsername("username");
authorityRepository.saveAuthority(authority);
assertNotNull(entityManager.find(Authority.class, 1));
}
@RunWith(SpringRunner.class)
@DataJpaTest ()
@Import(AuthorityRepositoryImpl.class)
public class AuthorityRepositoryTest2 {
@Autowired
AuthorityRepository authorityRepository;
@Autowired
TestEntityManager testEntityManager;
@Test
public void test() {
Authority authority = new Authority();
authority.setUsername("name");
authority.setUsername("username");
authorityRepository.saveAuthority(authority);
assertNotNull(testEntityManager.find(Authority.class, 1));
}