繁体   English   中英

我们应该在Spring Boot中为存储层编写单元测试和集成测试吗?

[英]Should we write unit test and integration test for repository layer in Spring Boot?

我对Spring Boot存储库层有很多疑问。

我的问题是:

  1. 我们是否应该在Spring Boot中为没有任何自定义代码或查询的存储库层编写单元测试和集成测试?
  2. Spring Boot为存储库层编写集成测试的最佳方法是什么? 我在下面列出了两种方法。 在这两种方法中,哪一种更好。 有什么最佳实践可以让我互相关注?
  3. 如果上述问题#1的答案为是,那么如何在Spring Boot为存储库层编写单元测试?

CurrencyRepository.java

@Repository
public interface CurrencyRepository extends CrudRepository<Currency, String> {

}

由于它使用嵌入式H2 DB,因此它是集成测试,而不是单元测试。 我的理解正确吗?

CurrencyRepositoryIntegrationTest.java(方法1)

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

    @Autowired
    private TestEntityManager entityManager;
    @Autowired
    private CurrencyRepository repository;

    @Test
    public void testFindByName() {
        entityManager.persist(new Currency("USD", "United States Dollar", 2L));
        Optional<Currency> c = repository.findById("USD");
        assertEquals("United States Dollar", c.get().getCcyNm());
    }

}

CurrencyRepositoryIntegrationTest2.java(方法2)

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class CurrencyRepositoryIntegrationTest2 {

    @Autowired
    private CurrencyRepository repository;

    @Test
    public void testFindByName() {
        repository.save(new Currency("USD", "United States Dollar", 2L));
        Optional<Currency> c = repository.findById("USD");
        assertEquals("United States Dollar", c.get().getCcyNm());
    }

}

对于集成测试,有句老话:“不要嘲笑自己不拥有的东西”。 参见例如https://markhneedham.com/blog/2009/12/13/tdd-only-mock-types-you-own/https://8thlight.com/blog/eric-smith/2011/10/27 /thats-not-yours.html

您将编写的JUnit测试将模拟基础EntityManger来测试spring是否正确实现。 这是我们希望Spring开发人员已经拥有的测试,所以我不再重复。

对于集成测试,我想您不在乎存储库如何或是否在下面使用EntityManager。 您只想查看它的行为是否正确。 因此,第二种方法更合适。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM