gpt4 book ai didi

java - 具有 Spring bean 依赖关系的 Junit/Mockito 单元

转载 作者:行者123 更新时间:2023-12-01 23:05:36 26 4
gpt4 key购买 nike

我需要在 ProductManager 类(一个 Spring bean)中测试以下方法。 ProductService 一个 bean 并注入(inject)到 ProductManager 类中。我尝试使用 Mockito 编写 Junit 测试,但它仍然调用真正的 ProductService.getProductIdList(email) 方法而不是模拟方法。 ProductService 还有一个 @PostConstruct。谁能告诉我我的测试代码有什么问题吗?

@Named(ProductManager.NAME)
public class ProductManager {

@Resource(name = ProductService.NAME)
private ProductService productService;

public static final String NAME = "productManager";

public Set<Product> getProducts(String email) {
Set<Integer> productList = productService.getProductIdList(email);
Iterator<Integer> itr = productList.iterator();
Set<Product> products = new HashSet<Product>();
Product p = null;
while (itr.hasNext()) {
p = getProduct(itr.next());
if (p != null) {
products.add(p);
}
}
return products;
}


public Product getProduct(Integer ProductId) {
Product p = productService.getProduct(productId);
return p;
}

}

到目前为止,我有以下 Junit 测试代码。

@Test
public void getProductByEmail(){

String email = "testfakeuser@gmail.com";

ProductService mockProductService = mock(ProductServiceImpl.class);

Integer productId1 = 10000;
Integer productId2 = 10002;

Product p1 = mock(Product.class);
Product p2 = mock(Product.class);
when(p1.getProductId()).thenReturn(productId1);
when(p2.getProductId()).thenReturn(productId2);

Set<Integer> productIdSet = (Set<Integer>)mock(Set.class);
productIdSet.add(productId1);
productIdSet.add(productId2);
Iterator<Integer> productIdIterator = (Iterator<Integer>)mock(Iterator.class);
when(productIdSet.iterator()).thenReturn(productIdIterator);
when(mockProductService.getProductIdList(email)).thenReturn(productIdSet);
when(productIdIterator.hasNext()).thenReturn(true, true, false);
when(productIdIterator.next()).thenReturn(productId1).thenReturn(productId2);
when(productManager.getProduct(productId1)).thenReturn(p1);
when(productManager.getProduct(productId2)).thenReturn(p2);

Set<Product> products = productManager.getProducts(email);
assertEquals(2, products.size());

}

最佳答案

我没有看到您将模拟的 ProductService 设置到 ProductManager 对象的任何位置。

您创建了一组复杂的相关对象,但没有要求 ProductManager 使用它。

关于java - 具有 Spring bean 依赖关系的 Junit/Mockito 单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22823958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com