gpt4 book ai didi

java - 如何使用mockito模拟exchange.getIn().getBody(HttpServletResponse.class)

转载 作者:行者123 更新时间:2023-12-02 01:18:32 27 4
gpt4 key购买 nike

我正在尝试用camel编写junit文件。

下面是我想模拟的 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 为 null。

最佳答案

您应该为 exchange.getIn()message.getBody(HttpServletResponse.class) 添加 when(...)。我建议您使用 @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

关于java - 如何使用mockito模拟exchange.getIn().getBody(HttpServletResponse.class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58160879/

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