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

标签 java spring unit-testing spring-boot spring-boot-test

我有很多关于 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());
    }

}

最佳答案

对于集成测试,有句老话“不要 mock 你不拥有的东西”。 参见例如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。您只是想看看它的行为是否正确。所以第二种方法更适合。

关于java - 我们应该在 Spring Boot 中为存储库层编写单元测试和集成测试吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55067063/

相关文章:

java - 正在 http 发布文件,如何通过索引引用参数?

c# - 具有带参数的虚拟测试方法的 xUnit 抽象测试类

python - 模拟还是 stub ?

java - 如何使用 Java7 try-with-resources 特性将资源作为参数传递

java - 将 KeyStore 与 .crt 一起使用

java - 使用 Spring 在特定日期(每个月的第一天)运行计时器任务

java - 根据请求体中的数据转发http请求

使用 jest 进行 javascript 单元测试 : how to mock async call

java - 文本文件打印 Java Applet 在 Windows 操作系统中无法运行

java - 我有一个非常奇怪的问题,url 被附加在查询字符串中