我正在尝试将骆驼文件写在骆驼上。

下面要模拟的servletResponse。

处理器:

HttpServletResponse servletResponse = exchange.getIn().getBody(HttpServletResponse.class);

ServletOutputStream servletOutputStream = servletResponse.getOutputStream();

IOUtils.copy(inputStream, servletOutputStream);

servletOutputStream.flush();
servletOutputStream.close();


我试图为此编写junit。

下面的代码模拟了ServletResponse:

HttpServletResponse response = mock(HttpServletResponse.class);

ServletOutputStream outputStream = mock(ServletOutputStream.class);

when(response.getOutputStream()).thenReturn(outputStream);


但是对于处理器中的servletResponse来说却是空的。

最佳答案

您应该为when(...)exchange.getIn()添加message.getBody(HttpServletResponse.class)。我建议您使用@RunWith(MockitoJUnitRunner.class)@Mock批注。看一下测试:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MyExchangeServiceTest {
    private MyExchangeService testedObject = new MyExchangeService();

    @Mock
    private Exchange exchange;
    @Mock
    private HttpServletResponse response;
    @Mock
    private Message message;
    @Mock
    private ServletOutputStream outputStream;

    @Test
    public void servletResponseIsRead() throws Exception {
        when(exchange.getIn()).thenReturn(message);
        when(message.getBody(HttpServletResponse.class)).thenReturn(response);
        when(response.getOutputStream()).thenReturn(outputStream);

        testedObject.process(exchange);
    }
}

更新,这是我的服务:
import org.apache.camel.Exchange;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class MyExchangeService {

    public void process(Exchange exchange) throws Exception {
        HttpServletResponse servletResponse = exchange.getIn().getBody(HttpServletResponse.class);

        servletResponse.setStatus(200);

        servletResponse.addHeader("Content-Type", "application/octet-stream");

        servletResponse.addHeader("Content-Disposition", "attachment;filename='xyz.csv'");

        ServletOutputStream servletOutputStream = servletResponse.getOutputStream();

        System.out.println(" servletOutputStream: " + servletOutputStream.getClass());
    }
}

测试输出:
 servletOutputStream: class org.mockito.codegen.ServletOutputStream$MockitoMock$501469028

10-08 08:49