【问题标题】:Cannot get Unit Test's thenReturn() value in Java无法在 Java 中获取单元测试的 thenReturn() 值
【发布时间】:2021-06-28 00:34:51
【问题描述】:

我有以下服务和测试方法:

ProductServiceImpl:

public List<ProductDTO> findAllByCategoryUuid(UUID categoryUuid) {

    // code omitted

    return result;
}

ProductServiceImplTest:

@Spy
@Autowired 
ProductServiceImpl productService;

@Mock
ProductRepository productRepository;

// ... other mock repositories
  

@Test
public void testFindAllByCategoryUuid() {

    UUID categoryUuid = UUID.randomUUID();

    final List<Product> productList = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        // create product by setting "categoryUuid" and add to productList
    }
    when(productRepository.saveAll(productList)).thenReturn(productList); // ?


    List<ProductDTO> response = new ArrayList<>();
    doReturn(response).when(productService).findAllByCategoryUuid(categoryUuid); // ?
}

虽然我创建了具有正确categoryUuid 关系的模拟产品,但我无法通过相同的categoryUuidfindAllByCategoryUuid 方法检索这些模拟产品总是返回空列表。那么,我该如何解决?以及如何正确使用上面的whendoReturn 方法?

【问题讨论】:

  • 您使用@Spy的原因是什么?此外,您可能需要使用@MockBean。最后,在大多数情况下,如果您使用构造函数注入,则不需要 Spring 进行单元测试;只需将您的模拟传递给被测类的构造函数即可。
  • 为什么productService 上有doReturn?这不是您要测试的对象吗?您的测试也没有断言。在findAllByCategoryUuid 中的productRepository 上调用了哪个方法?是saveAll吗?
  • @chrylis-cautiouslyoptimistic- 为什么不通过更新我的代码作为答案来发布示例?
  • 因为我对您的代码的作用还不够了解,无法给您答案。例如,在我理解你为什么选择使用doReturn(response).when(productService)... 之前,我可能并不真正理解你想要做什么。
  • 我的问题不是你为什么使用doReturn而不是when,而是你为什么要嘲笑被测类的行为。

标签: java spring-boot unit-testing testing mocking


【解决方案1】:

你通常会这样做:

public class ProductServiceImplTest {

  // create an actual instance of the class you want to test, with its dependencies supplied by mocks
  @InjectMocks
  ProductServiceImpl productService;

  // This will be injected into productService;
  @Mock
  ProductRepository productRepository;

  @Test
  public void testSomeAspectOfProductServiceImplBehaviour() {
    // tell the productRepository mock to respond as necessary for the test
    when(productRepository.something()).thenReturn(...);
    // call the method you want to test and check that the result is as expected
    assertThat(productService.someMethod(), Matchers.equalTo(...);
  }
}

【讨论】:

  • 非常有用的解释,投了赞成票。另一方面,如果您有时间,添加一些示例模拟 bean 及其用法(我需要设置一些属性的 bean 和只是模拟 bean 的 bean)会更有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多