首页 > 解决方案 > 无法在 Java 中获取单元测试的 thenReturn() 值

问题描述

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

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关系的模拟产品,但我无法通过相同的方式检索这些模拟产品,categoryUuid并且findAllByCategoryUuid方法总是返回空列表。那么,我该如何解决?我应该如何正确使用when上述doReturn方法?

标签: javaspring-bootunit-testingtestingmocking

解决方案


你通常会做这样的事情:

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(...);
  }
}

推荐阅读