首页 > 解决方案 > 单元测试中私有方法返回的值

问题描述

我的服务中有类似的方法,如下所示:

public List<ProductDTO> findById(final int id) {
    final List<String> categoryList = getCategoryById(id);
    final List<UUID> productUuidList = 
        productRepository.findAllUuidByCategoryIdIn(categoryList);
    return getProductDTOList();
}

private static List<String> getCategoryById(final int id) {

    // code omitted
    return ...
}

我有一个单元测试findById方法,如下所示。

@Test
public void test_findByZoneOffset() {

    List<String> categoryList = new ArrayList<>();
    // code omitted (fill categoryList with proper values)

    final List<UUID> productUuidList = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        productUuidList.add(UUID.randomUUID());
    }

    when(productRepository.findAllUuidByCategoryIdIn(categoryList))
        .thenReturn(productUuidList);

    // code omitted
    

    final List<ProductDTO> productDTOList = productService.findById(5);
}

但是,我不能创建categoryList与方法返回的相同值,getCategoryById()因为它是私有方法。另一方面,由于该私有方法中没有服务或存储库调用,我不想从单元测试方法中调用它,只想创建一个模拟categoryList和 make categoryListinfindById方法是相同的。那么,我该怎么做呢?

标签: javaunit-testingjunitmockingjunit5

解决方案


推荐阅读