我正在使用Mockito和Junit来测试应用程序,我需要在模拟时向HttpServletRequest添加标头。这是我第一次使用模拟概念来测试应用程序。在使用这个模拟概念时,我们如何设置标题来请求对象?
Java代码:
@Produces({ MediaType.APPLICATION_JSON })
@Path("/devices")
public class DvrRestService {
private static final Logger logger = LoggerFactory.getLogger(DvrRestService.class);
private DvrMiddleService dvrMiddleService;
@Inject
public DvrRestService(DvrMiddleService dvrMiddleService) {
this.dvrMiddleService = dvrMiddleService;
}
@GET
@Path("/{deviceId}/metadata")
public Response getDeviceMetadata(@Context HttpServletRequest request, @PathParam("deviceId") String deviceId,
@RequiredSession final Session session) {
try {
public static String[] REQUEST_HEADERS = { "if-none-match" };
List<String> requiredHeaders = Lists.newArrayList(REQUEST_HEADERS);
Map<String, String> headers = new HashMap<String, String>();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) { // here gettting NullPointerException
String headerName = headerNames.nextElement();
if (requiredHeaders.contains(headerName.toLowerCase())) {
String value = request.getHeader(headerName);
if (value != null) {
headers.put(headerName, value);
System.out.println("headerName: " + headerName + ", Value: " + value);
}
}
}
DvrResponse response = dvrMiddleService.getDeviceMetadata(deviceId.toUpperCase(), getHeaders(request));
return processResponse(response.statusCode, response.getResponse(), DeviceMetadataResponse.class,
response.getHeaders());
} catch (Exception e) {
return processErrorResponse(e, new DeviceMetadataResponse(), logger);
}
}
}
这是我的测试代码:
public class DvrRestServiceTest {
static DvrMiddleService dms;
static HttpServletRequest request;
static Session session;
static DvrRestService drs;
public static final String DeviceId = "000004D42070";
@BeforeClass
public static void init(){
dms = mock(DvrMiddleService.class);
request = mock(HttpServletRequest.class);
session = mock(Session.class);
drs = new DvrRestService(dms);
}
@Test
public void getDeviceMetadataTest(){
Response rs = drs.getDeviceMetadata(request, DeviceId, session);
assertEquals(Response.Status.OK, rs.getStatus());
}
}
答案 0 :(得分:11)
作为校长的起点和演示,您可以从以下片段开始。
// define the headers you want to be returned
Map<String, String> headers = new HashMap<>();
headers.put(null, "HTTP/1.1 200 OK");
headers.put("Content-Type", "text/html");
// create an Enumeration over the header keys
Iterator<String> iterator = headers.keySet().iterator();
Enumeration headerNames = new Enumeration<String>() {
@Override
public boolean hasMoreElements() {
return iterator.hasNext();
}
@Override
public String nextElement() {
return iterator.next();
}
};
// mock HttpServletRequest
HttpServletRequest request = mock(HttpServletRequest.class);
// mock the returned value of request.getHeaderNames()
when(request.getHeaderNames()).thenReturn(headerNames);
System.out.println("demonstrate output of request.getHeaderNames()");
while (headerNames.hasMoreElements()) {
System.out.println("header name: " + headerNames.nextElement());
}
// mock the returned value of request.getHeader(String name)
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return headers.get((String) args[0]);
}
}).when(request).getHeader("Content-Type");
System.out.println("demonstrate output of request.getHeader(String name)");
String headerName = "Content-Type";
System.out.printf("header name: [%s] value: [%s]%n",
headerName, request.getHeader(headerName));
}
输出
demonstrate output of request.getHeaderNames()
header name: null
header name: Content-Type
demonstrate output of request.getHeader(String name)
header name: [Content-Type] value: [text/html]
答案 1 :(得分:1)
HttpServletRequest
是一个复杂的接口,有 20 多个方法,它们之间有明确定义的相互作用。与其仔细模拟您正在使用的那些,另一种方法是使用已经具有完整功能模拟类型的库。
spring-test
库有一个 MockHttpServletRequest
类就是这样做的。虽然该库是为测试 Spring 应用程序而设计的,但即使应用程序不使用 Spring,MockHttpServletRequest
类本身也应该完全可用。
@BeforeClass
public static void init(){
// ...
MockHttpServletRequest mockRequest = new MockHttpServletRequest();
request.addHeader("Content-Type", "text/html");
request.addHeader("customHeader", "customValue");
this.request = mockRequest;
}
答案 2 :(得分:0)
我知道OP正在使用Mockito。此答案适用于使用spock的用户。您可以轻松完成此操作。
class MyTestSpec extends Specification {
HttpServletRequest request = Mock()
MyTestClass myTestClass = new MyTestClass()
def 'my test'() {
setup:
String expectedHeader = "x-mycustom-header"
when:
String someResult = myTestClass.someTestMethod()
then:
// here is where you return your header from the mocked request
1 * request.getHeader(_ as String) >> expectedHeader
}
}