gpt4 book ai didi

java - 在 Mockito 中捕获一个参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:26 30 4
gpt4 key购买 nike

我正在测试某个类。此类在内部实例化一个“GetMethod”对象,该对象传递给“HttpClient”对象,该对象被注入(inject)到测试类中。

我正在模拟“HttpClient”类,但我也需要修改“GetMethod”类的一个方法的行为。我正在玩 ArgumentCaptor,但我似乎无法在“when”调用中获取实例化对象。

例子:

HttpClient mockHttpClient = mock(HttpClient.class);
ArgumentCaptor<GetMethod> getMethod = ArgumentCaptor.forClass(GetMethod.class);
when(mockHttpClient.executeMethod(getMethod.capture())).thenReturn(HttpStatus.SC_OK);
when(getMethod.getValue().getResponseBodyAsStream()).thenReturn(new FileInputStream(source));

响应:

org.mockito.exceptions.base.MockitoException: 
No argument value was captured!
You might have forgotten to use argument.capture() in verify()...
...or you used capture() in stubbing but stubbed method was not called.
Be aware that it is recommended to use capture() only with verify()

最佳答案

您不能在 getMethod 上使用 when,因为 getMethod 不是模拟。它仍然是您的类创建的真实对象。

ArgumentCaptor 有完全不同的用途。检查section 15 here .

您可以使您的代码更易于测试。通常,创建其他类的新实例的类很难测试。将一些工厂放入此类中以创建 get/post 方法,然后在测试中模拟该工厂,并使其模拟 get/post 方法。

public class YourClass {
MethodFactory mf;

public YourClass(MethodFactory mf) {
this.mf = mf;
}

public void handleHttpClient(HttpClient httpClient) {
httpClient.executeMethod(mf.createMethod());
//your code here
}
}

然后在测试中你可以这样做:

HttpClient mockHttpClient = mock(HttpClient.class);
when(mockHttpClient.executeMethod(any(GetMethod.class)).thenReturn(HttpStatus.SC_OK);

MethodFactory factory = mock(MethodFactory.class);
GetMethod get = mock(GetMethod.class);
when(factory.createMethod()).thenReturn(get);
when(get.getResponseBodyAsStream()).thenReturn(new FileInputStream(source));

更新

您还可以尝试一些讨厌的黑客攻击,Answer 并通过反射访问 GetMethod 的私有(private)部分 ;)。 (这真是令人讨厌的 hack)

when(mockHttpClient.executeMethod(any(GetMethod.class))).thenAnswer(new Answer() {
Object answer(InvocationOnMock invocation) {
GetMethod getMethod = (GetMethod) invocation.getArguments()[0];

Field respStream = HttpMethodBase.class.getDeclaredField("responseStream");
respStream.setAccessible(true);
respStream.set(getMethod, new FileInputStream(source));

return HttpStatus.SC_OK;
}
});

关于java - 在 Mockito 中捕获一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3620796/

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