我正在尝试使用服务器端resteasy模拟框架来发出GET请求,但是当尝试从服务器代码中检索标头时,它根本就不存在。
以下是测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:base-spring-context.xml" }, loader = DelegatingSmartContextLoader.class)
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestClass {
// Sets up RESTEasy processors to test @Provider classes
@Configuration
static class ContextConfiguration {
@Autowired
private ApplicationContext context;
@Bean
public Dispatcher getDispatcher() {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addResourceFactory(getSpringResourceFactory());
return dispatcher;
}
@Bean
public SpringBeanProcessor getRSPostProcessor() {
SpringBeanProcessor processor = new SpringBeanProcessor(getDispatcher(), getDispatcher().getRegistry(),
getDispatcher().getProviderFactory());
return processor;
}
@Bean
public SpringResourceFactory getSpringResourceFactory() {
SpringResourceFactory noDefaults = new SpringResourceFactory("restClass", context,
RestClass.class);
return noDefaults;
}
}
@Autowired
Dispatcher dispatcher;
@Autowired
private ServletContext servletContext;
@Before
public void setUp() {
ResteasyProviderFactory.getContextDataMap().put(HttpServletRequest.class, new MockHttpServletRequest(servletContext));
}
@Test
public void testRest() throws URISyntaxException, ECUNotFoundException {
MockHttpRequest request = MockHttpRequest.get("/")
.header("someHeader", "VALUE")
.accept("application/myValue+XML");
logger.info("HEADERS: {}",request.getHttpHeaders().getRequestHeader("someHeader"));
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
logger.info("Got response: \n\tStatus: '{}'\n\tResponse body: '{}'",response.getStatus(),new String(response.getOutput()));
}
}
以下是从RestClass
触发Rest方法的方法@GET
@Path("/")
@Produces("application/myValue+XML")
@GZIP
public Response getMethod(@Context HttpServletRequest request) {
String header = request.getHeader("someHeader");
logger.info("HEADER NAME: {}","someHeader");
if (header == null || header.isEmpty()) {
logger.warn("the header must be present in the request");
return Response.status(Status.BAD_REQUEST).build();
}
这里的问题是Rest方法没有收到标题。但是,当测试方法的打印输出清楚地显示标题已设置时,它为空。
任何人都可以帮助理解为什么会这样。