Mockito:返回传递的参数

时间:2015-01-26 09:48:02

标签: java mocking mockito apache-httpclient-4.x

我有一个模拟对象:

HttpUriRequest request = Mockito.mock(HttpUriRequest.class);

我的代码调用

request.setHeader(key, value);

当调用value方法时,模拟如何返回getFirstHeader()

request.getFirstHeader(key).getValue();

key和预期回报valuesetHeader调用的参数?

request.getFirstHeader(key)返回Header类型的对象,该对象的方法为getValue()

3 个答案:

答案 0 :(得分:1)

或者,你可能想要间谍'在一个真实的物体而不是嘲笑它。

HttpGet request = Mockito.spy(new HttpGet("/"));
request.setHeader(key, value);

Mockito.verify(request).getFirstHeader(key);

答案 1 :(得分:1)

我找到了解决自己问题的方法:

    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;
}

答案 2 :(得分:0)

这是一个代码,我认为这是一个很好的暗示。

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());

    }
}

如果代码无法帮助您,请告诉我