You cannot use when in getMethod because getMethod is not a layout. This is still the real object created by your class.
ArgumentCaptor has a completely different purpose. Mark section 15 here .
You can make your code more verifiable. As a rule, classes that create new instances of other classes are difficult to verify. Put some factory in this class to create get / post methods, then in the mock this factory test and make it a false get / post method.
public class YourClass { MethodFactory mf; public YourClass(MethodFactory mf) { this.mf = mf; } public void handleHttpClient(HttpClient httpClient) { httpClient.executeMethod(mf.createMethod());
Then in the test you can do:
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));
UPDATE
You can also try a few nasty hacks and Answer and access the private parts of GetMethod;) by reflection. (This is a really nasty 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; } });
amorfis
source share