gpt4 book ai didi

java - 进行单元测试时来自 Mockito 的 MissingMethodInitationException

转载 作者:行者123 更新时间:2023-12-01 10:55:59 25 4
gpt4 key购买 nike

我有一个类,其中包含一个公共(public)静态方法getProduct(String name):

public class ProductManager {
public static Product getProduct(String name) {
Product prod = findProduct(name);
return prod;
}
}

另一个CustomerService类使用上面的ProductManager:

public class CustomerService {
...
public void handleProduct() {
Product appleProd = ProductManager.getProduct("apple");
doHandle(appleProd);
}
}

我在 CustomerService 类中对 handleProduct() 方法进行单元测试。我用mockito模拟测试中的 ProductManager.getProduct("apple") 部分:

public class CustomerServiceTest {
@Test
public void testHandleProduct() {
Product mockProd = Mockito.mock(Product.class);

// MissingMethodInvocationException
when(ProductManager.getProduct("apple")).thenReturn(mockProd);
...
}
}

但是,当我运行测试时,我从 Mockito 得到了 MissingMethodInitationException:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

它提示在 when() 内部我没有调用方法,但我确实调用了 public static 方法 ProductManager.getProduct("apple") in when(...),为什么 Mockito 向我提出这个错误?我不明白。

最佳答案

Mockito 无法模拟静态方法。使它成为一个实例方法,您的代码就可以工作。

还有其他框架允许这样做(例如 Powermock),但是这是相当糟糕的做法,也是糟糕设计的标志。您应该创建一个实例并进行依赖项注入(inject)。如果一个方法很小,可以在测试其他类时间接测试它(例如 Math.max()),则不需要模拟。

在您发布的代码中,您有 getProduct(),但在堆栈跟踪中它是 getArticles() - 我认为该代码只是一个简化的示例,而堆栈跟踪是实际的。

这里有几篇文章解释了测试/模拟静态方法的问题:

关于java - 进行单元测试时来自 Mockito 的 MissingMethodInitationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33606719/

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