Reputation: 15683
I have a mock object:
HttpUriRequest request = Mockito.mock(HttpUriRequest.class);
on which my code calls
request.setHeader(key, value);
How can the mock return the value
when the getFirstHeader()
method is called
request.getFirstHeader(key).getValue();
where the key
and the expected return value
are the parameters from the setHeader
invocation ?
request.getFirstHeader(key)
returns an object of type Header
which has a method getValue()
Upvotes: 1
Views: 1582
Reputation: 15683
I found a solution to my own problem:
final MutableWrapper<String> stringWrapper = new MutableWrapper<>();
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
stringWrapper.wrap(invocation.getArgumentAt(1, String.class));
return null;
}
}).when(request).setHeader(Matchers.eq(HEADER), Matchers.anyString());
Mockito.doAnswer(new Answer<Header>() {
@Override
public Header answer(InvocationOnMock invocation) throws Throwable {
Header header = Mockito.mock(Header.class);
Mockito.when(header.getValue()).thenReturn(stringWrapper.unwrap());
return header;
}
}).when(request).getFirstHeader(Matchers.eq(HEADER));
return request;
}
Upvotes: 1
Reputation: 27583
Alternatively, you might want to 'spy' on a real object instead of mocking it.
HttpGet request = Mockito.spy(new HttpGet("/"));
request.setHeader(key, value);
Mockito.verify(request).getFirstHeader(key);
Upvotes: 1
Reputation: 439
Here is a code that i think is a good hint for you.
import org.junit.*;
import org.mockito.Mockito;
/**
* Created by soroosh on 1/26/15.
*/
public class MockitoTest {
@org.junit.Test
public void ttt(){
class HttpUriRequest{
public String getFirstHeader(){
return "Header";
}
}
HttpUriRequest request = Mockito.mock(HttpUriRequest.class);
Mockito.when(request.getFirstHeader()).thenReturn("yoohoo");
System.out.println(request.getFirstHeader());
}
}
Let me know if the code could not help you
Upvotes: 0