gpt4 book ai didi

java - Mockito 缺少方法调用异常

转载 作者:行者123 更新时间:2023-11-30 02:57:21 28 4
gpt4 key购买 nike

我知道有很多与我的问题类似的问题/答案,但我仍然无法通过测试解决此问题。

问题:我试图模拟 Settings 类,但 Mockito 提示这一行:

when(settings.settingsBuilder().put(new String("test"), "test").build()).thenReturn(settings)

任务方法调用异常:

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.

我尝试了多种可能的方法,但没有结果。以下为实际测试方法。

@RunWith(PowerMockRunner.class)
@PrepareForTest({Settings.class, Client.class})
public class AddressMatcherElasticTest {

private final AddressWebConfiguration configuration = mock(AddressWebConfiguration.class);
private final Settings settings = mock(Settings.class);
private final Client client = mock(Client.class);

@Test
public void match() throws Exception {
when(configuration.getClusterName()).thenReturn(new String("name"));
when(settings.settingsBuilder().put(new String("name"), "test").build()).thenReturn(settings);
AddressMatcherElastic test = new AddressMatcherElastic(configuration);
verify(configuration, times(1)).getClusterName();
}
}

最佳答案

settings 是您的模拟,您可以告诉 Mockito 在调用它时返回什么。

然而,

settings.settingsBuilder() 不会返回模拟,这就是 Mockito 所提示的。您可以告诉Mockito在调用settingsBuilder时返回一个模拟对象,例如

Builder settingsBuilder = mock(Builder.class);
when(settingsBuilder.doX()).thenReturn(...);
when(settings.settingsBuilder()).thenReturn(settingsBuilder);

如果您没有另外声明,请注意,您的模拟将默认为对象引用返回 null。

关于java - Mockito 缺少方法调用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36865412/

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