i want to create an embedded jetty server (not maven, gradle etc.) to test a spring rest service.
Therefor i created an EmbeddedServer class. But unfortunately invocation of the rest service leads always to an http 404 error. What doing wrong?
The rest service works fine with tomcat (not embedded).
Im using the following dependencies:
"org.eclipse.jetty:jetty-server:8.1.17.v20150415"
"org.eclipse.jetty:jetty-webapp:8.1.17.v20150415"
Here is the EmbededServer class:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class EmbeddedServer {
private Server server;
public void start() throws Exception {
this.server = createServer();
this.server.start();
}
public void stop() throws Exception {
this.server.stop();
this.server.join();
this.server.destroy();
}
private Server createServer() {
final Server server = new Server(8080);
final WebAppContext context = new WebAppContext();
context.setContextPath("/");
context.setResourceBase("src/main/webapp");
context.setDescriptor("src/main/webapp/WEB-INF/web.xml");
context.setParentLoaderPriority(true);
context.setServer(server);
server.setHandler(context);
return server;
}
}
And the test class:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class SimpleTest {
private HttpClient client;
private EmbeddedServer server;
#Before
public void before() throws Exception {
this.client = new DefaultHttpClient();
this.server = new EmbeddedServer();
this.server.start();
}
#After
public void after() throws Exception {
this.server.stop();
}
#Test
public void invokeHello() throws Exception {
final HttpResponse response = invokeGetRequest("http://localhost:8080/hello");
verifyResponse(response, 200, "hello");
}
private HttpResponse invokeGetRequest(final String path) throws Exception {
final URI wsAddress = new URI(path);
final HttpGet method = new HttpGet(wsAddress);
return this.client.execute(method);
}
private void verifyResponse(final HttpResponse actualHttpResponse, final int expectedHttpCode, final String expectedResponse) throws IOException {
assertThat(actualHttpResponse.getStatusLine().getStatusCode(), equalTo(expectedHttpCode));
final String actualResponse = EntityUtils.toString(actualHttpResponse.getEntity(), "UTF-8");
assertThat(actualResponse, equalTo(expectedResponse));
}
}
This test fails with:
java.lang.AssertionError:
Expected: <200>
but: was <404>
Path of ResourceBase and Descriptor must be absolute.
context.setResourceBase("c:/myapp/src/main/webapp");
context.setDescriptor("c:/myapp/src/main/webapp/WEB-INF/web.xml");
Related
The next code is the netty http server handler, it can operation normally.
package com.sunquakes.jsonrpc4j.server;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.springframework.context.ApplicationContext;
public class JsonRpcNettyHttpServerHandler extends ChannelInboundHandlerAdapter {
private ApplicationContext applicationContext;
public JsonRpcNettyHttpServerHandler(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
FullHttpRequest httpRequest = (FullHttpRequest) msg;
ByteBuf buf = httpRequest.content();
HttpMethod method = httpRequest.method();
if (!HttpMethod.POST.equals(method)) {
send(ctx, "", HttpResponseStatus.METHOD_NOT_ALLOWED);
return;
}
String body = buf.toString(CharsetUtil.UTF_8);
JsonRpcServerHandler jsonRpcServerHandler = new JsonRpcServerHandler(applicationContext);
Object res = jsonRpcServerHandler.handle(body);
String output = JSON.toJSONString(res);
send(ctx, output, HttpResponseStatus.OK);
httpRequest.release();
}
private void send(ChannelHandlerContext ctx, String context, HttpResponseStatus status) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8");
response.headers().set(HttpHeaderNames.CONNECTION, "keep-alive");
ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}
But when I drop .addListener(ChannelFutureListener.CLOSE), The client won't receive message. I want to keep the channel keepalive. What can I do.
Here's what I'm trying to do:
Set up a Tomcat 7 server programmatically - that works with a simple servlet. I'm defining Tomcat's endpoints from within the code only, there are no settings nor routers on the file system (this is a constraint).
Have the said Tomcat server include a websocket server endpoint using Javax Websockets API (1.1) - that doesn't work.
My app/server entry point:
package com.myapp;
import java.io.File;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.deploy.FilterDef;
import org.apache.catalina.deploy.FilterMap;
import org.apache.catalina.startup.Tomcat;
public class App
{
public static void main(String[] args) throws LifecycleException
{
int port = 8080;
Tomcat webServer = new Tomcat();
webServer.setPort(port);
webServer.setHostname("localhost");
String appBase = ".";
webServer.getHost().setAppBase(appBase);
File docBase = new File(System.getProperty("java.io.tmpdir"));
Context context = webServer.addContext("", docBase.getAbsolutePath());
// both MyServlet and MyFilter exist and work.
Class servletClass = MyServlet.class;
Tomcat.addServlet(context, servletClass.getSimpleName(), servletClass.getName());
context.addServletMapping("/my-servlet/*", servletClass.getSimpleName());
Class filterClass = MyFilter.class;
FilterDef myFilterDef = new FilterDef();
myFilterDef.setFilterClass(filterClass.getName());
myFilterDef.setFilterName(filterClass.getSimpleName());
context.addFilterDef(myFilterDef);
FilterMap myFilterMap = new FilterMap();
myFilterMap.setFilterName(filterClass.getSimpleName());
myFilterMap.addURLPattern("/my-servlet/*");
context.addFilterMap(myFilterMap);
webServer.start();
webServer.getServer().await();
}
}
My websocket server endpoint class:
package com.myapp;
import java.nio.ByteBuffer;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/web-socket/")
public class WebSocket
{
#OnOpen
public void onOpen()
{
System.out.println("Open Connection ...");
}
#OnMessage
public static void onTextMessage(Session session, String msg) {
System.out.println("On Message for Web Socket");
}
#OnMessage
public void onBinaryMessage(Session session, ByteBuffer msg){
System.out.println("On Message for Web Socket");
}
#OnMessage
public void onPongMessage(Session session, PongMessage pMsg) {
System.out.println("On Message for Web Socket");
}
#OnClose
public void onClose(Session session) {
System.out.println("Connection Close for Web Socket");
}
#OnError
public void onError(Throwable e)
{
e.printStackTrace();
}
}
I'm using Maven, and I'm including the WebSocket API with <scope>provided</scope>, as I've seen in other questions that this was the root of other problems.
When I run the server, I can hit the my-servlet endpoint successfully (as a web page, of course), but when I try to create a WS object, simply within the browser's dev console using var webSocket = new WebSocket("ws://localhost:8080/web-socket"), it says that it can't hit the endpoint:
WebSocket connection to 'ws://localhost:8080/web-socket' failed: Error during WebSocket handshake: Unexpected response code: 404
My question: What am I missing? The error message (from Chrome) suggests that the endpoint isn't registered (hence the 404). How do I register the websocket ServerEndpoint? Thanks!
EDIT:
Here's my implementation of MyServlet class:
package com.myapp;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet
{
#Override
protected void doGet(
HttpServletRequest req,
HttpServletResponse resp) throws IOException
{
resp.setStatus(HttpServletResponse.SC_OK);
resp.getWriter().write("Works...");
resp.getWriter().flush();
resp.getWriter().close();
}
}
And here's my implementation of MyFilter:
package com.myapp;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class MyFilter implements Filter
{
#Override
public void init(FilterConfig filterConfig)
{
// ...
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.addHeader("myHeader", "myHeaderValue");
chain.doFilter(request, httpResponse);
}
#Override
public void destroy()
{
// ...
}
}
Try this to manually add web socket endpoint:
String serverContainerClass = ServerContainer.class.getName();
//should be "javax.websocket.server.ServerContainer", if not, some external package could have hogged the implementation
final ServerContainer serverContainer = (ServerContainer) context.getServletContext().getAttribute(serverContainerClass);
try
{
serverContainer.addEndpoint(WebSocket.class);
}
catch (DeploymentException e)
{
TraceWriter.Error(this, "Failed to initialize websocket", e);
}
You should put this code after you add servlet to context
I am trying to set timeout for WS call. I extended WebServiceGatewaySupport and was trying to set to Sender timeout like this:
public Object marshalSendAndReceive(Object requestPayload) {
WebServiceTemplate wsTemplate = this.getWebServiceTemplate();
for (WebServiceMessageSender sender : wsTemplate.getMessageSenders()) {
try {
HttpComponentsMessageSender httpSender = (HttpComponentsMessageSender) sender;
httpSender.setReadTimeout(3000);
httpSender.setConnectionTimeout(2000);
} catch (ClassCastException | NumberFormatException cex) {
logger.warn("Cannot set WS timeout: " + cex.getMessage());
}
}
return wsTemplate.marshalSendAndReceive(requestPayload);
}
(credit to question #6733744)
However I get: Cannot set WS timeout: org.springframework.ws.transport.http.HttpsUrlConnectionMessageSender cannot be cast to org.springframework.ws.transport.http.HttpComponentsMessageSender
Can timeout be set to HttpsUrlConnectionMessageSender somehow? Or is there any other way to set timeout to https ws call in spring-boot?
Thank you.
I had the same issue, and managed to make it work using HttpComponentsMessageSender. Here is my code:
HttpComponentsMessageSender messageSender = new HttpComponentsMessageSender();
HttpClient httpClient = HttpClientFactory.getHttpsClient(sslUtils, timeout);
messageSender.setHttpClient(httpClient);
webServiceTemplate.setMessageSender(messageSender);
I also created a new factory class HttpClientFactory that sets the SSL and timeout:
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
public class HttpClientFactory {
private static CloseableHttpClient client;
private HttpClientFactory() {
}
public static HttpClient getHttpsClient(SslUtils sslUtils, int timeout) throws Exception {
if (client != null) {
return client;
}
SSLContext sslcontext = getSSLContext(sslUtils);
SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.addInterceptorFirst(new ContentLengthHeaderRemover());
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build();
return httpClientBuilder.setSSLSocketFactory(factory)
.setDefaultRequestConfig(config)
.build();
}
private static class ContentLengthHeaderRemover implements HttpRequestInterceptor {
#Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
request.removeHeaders(HTTP.CONTENT_LEN);
}
}
public static void releaseInstance() {
client = null;
}
private static SSLContext getSSLContext(SslUtils sslUtils) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(sslUtils.getKeystore().getInputStream(), sslUtils.getKeyPwd().toCharArray());
sslUtils.getKeystore().getInputStream().close();
KeyStore ts = KeyStore.getInstance("JKS");
ts.load(sslUtils.getTrustStore().getInputStream(), sslUtils.getTrustPwd().toCharArray());
sslUtils.getTrustStore().getInputStream().close();
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
try {
sslContextBuilder = SSLContexts.custom().loadKeyMaterial(ks, ssl.getKeyPwd().toCharArray());
} catch (UnrecoverableKeyException e) {
e.printStack();
}
sslContextBuilder.loadTrustMaterial(ts, new TrustSelfSignedStrategy());
return sslContextBuilder.build();
}
}
For information the SslUtils is just a bean class that holds the keystore and truststore informations' :
public class SslUtils {
private Resource keystore;
private String keyPwd;
private Resource trustStore;
private String trustPwd;
// Getters and Setters
}
This works for me and let me use both SSL and timeout at the same. I hope this will help others.
You're getting a cast exception because HttpsUrlConnectionMessageSender and HttpComponentsMessageSender are not compatible types. They both share the same superclass (WebServiceMessageSender), but you can't cast one to the other. I think you can just use a HttpComponentsMessageSender in your WebServiceTemplate configuration. See How to set timeout in Spring WebServiceTemplate and Spring webServiceTemplate connection timeout property
I have jersey project with spring. Now My test is deriverd from JerseyTest. When I try to do
#AutoWired
RestTemplate restTemplate;
It looks like spring is not working in jersey test. I did some research and found some links like
spring_jersey
but it did not work ,since I am using jersey2.0.
My code looks like
//AbstractTest
package com.test;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.server.validation.ValidationFeature;
public abstract class AbstractTest extends JerseyTest
{
protected WebTarget getRootTarget(final String rootResource)
{
return client().target(getBaseUri()).path(rootResource);
}
#Override
protected final Application configure()
{
final ResourceConfig application = configureApplication();
// needed for json serialization
application.register(JacksonFeature.class);
// bean validation
application.register(ValidationFeature.class);
// configure spring context
application.property("contextConfigLocation", "classpath:/META-INF/applicationContext.xml");
// disable bean validation for tests
application.property(ServerProperties.BV_FEATURE_DISABLE, "true");
return application;
}
protected abstract ResourceConfig configureApplication();
#Override
protected void configureClient(final ClientConfig config)
{
// needed for json serialization
config.register(JacksonFeature.class);
config.register(new LoggingFilter(java.util.logging.Logger.getLogger(AbstractResourceTest.class.getName()), false));
super.configureClient(config);
}
}
package com.test;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
//MyTest
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.match.MockRestRequestMatchers;
import org.springframework.web.client.RestTemplate;
import junit.framework.Assert;
public final class MyTest extends AbstractTest
{
private static final String ROOT_RESOURCE_PATH = "/testUrl";
#AutoWired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
#Before
public void setup(){
this.restTemplate = new RestTemplate();
this.mockServer = MockRestServiceServer.createServer(restTemplate);
}
#Test
public void testPostWithString() {
WebTarget target = getRootTarget(ROOT_RESOURCE_PATH).path("");
String entityBody = new String();
entityBody = " My test data";
final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(entityBody, "text/plain");
mockServer.expect(MockRestRequestMatchers.requestTo(ROOT_RESOURCE_PATH)).andExpect(method(HttpMethod.POST)).andExpect(content().string(entityBody))
.andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));
final Response response = target.request().post(entity);
Assert.assertNotNull("Response must not be null", response.getEntity());
Assert.assertEquals("Response does not have expected response code", 200, response.getStatus());
System.out.println("Response = " + response.getEntity());
String data = response.readEntity(String.class);
System.out.println("Response = " + data);
if(response.ok() != null)
{
System.out.println("Ok");
}
}
}
Update:
public class SimpleJerseyTest extends ApplicationContextAwareJerseyTest {
private static final String ROOT_RESOURCE_PATH = "/test";
#Override
public void configureApplication(ResourceConfig config) {
config.register(MyApp.class);
config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
}
#Before
public void setUp() {
try{
((ConfigurableApplicationContext)this.applicationContext).refresh();
super.setUp();
}catch(Exception e){
}
this.mockServer = MockRestServiceServer.createServer(restTemplate);
}
#Autowired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
#Test
public void doitOnce() {
WebTarget target = target(ROOT_RESOURCE_PATH);
String entityBody = new String();
final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(entityBody, "text/plain");
mockServer.expect(MockRestRequestMatchers.requestTo(ROOT_RESOURCE_PATH)).andExpect(method(HttpMethod.POST)).andExpect(content().string(entityBody))
.andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));
final Response response = target.request().post(entity);
System.out.println("Response = " + response.getEntity());
String data = response.readEntity(String.class);
System.out.println("Response = " + data);
if(response.ok() != null)
{
System.out.println("Ok");
}
}
}
I have added bean in
src/test/resources/META-INF/applicationContext.xml
<!-- Our REST Web Service client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
Same bean I have added in
src/main/resources/META-INF/applicationContext.xml
!-- Our REST Web Service client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
Instead of configuring Spring like this
application.property("contextConfigLocation", "classpath:/META-INF/applicationContext.xml");
You can instead use
application.property("contextConfig", <ApplicationContext>);
This way you can have an instance of the ApplicationContext, where you can get the AutowireCapableBeanFactory. With this, you can just call acbf.autowireBean(this) to inject the test class.
Here's what I mean. I tested it, and it works find for simple cases. Won't work well though if the beans you are trying to inject aren't singletons, as new one will be create for the test and where ever else you try to inject to in your application code
public abstract class ApplicationContextAwareJerseyTest extends JerseyTest {
protected ApplicationContext applicationContext;
#Override
protected final ResourceConfig configure() {
final ResourceConfig config = new ResourceConfig();
configureApplication(config);
this.applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
config.property("contextConfig", this.applicationContext);
final AutowireCapableBeanFactory bf = this.applicationContext.getAutowireCapableBeanFactory();
bf.autowireBean(this);
return config;
}
public final ApplicationContext getApplicationContext() {
return this.applicationContext;
}
protected void configureApplication(ResourceConfig resourceConfig) {};
}
One thing I am not sure about though is how the resetting would work. I tried to add
#Before
public void setUp() throws Exception {
((ConfigurableApplicationContext)this.applicationContext).refresh();
super.setUp();
}
into the abstract class, but that doesn't seem to work as expected. The test I used is as follows
public class SimpleJerseyTest extends ApplicationContextAwareJerseyTest {
#Path("test")
public static class SimpleResource {
#Autowired
private MessageService service;
#GET
public String getMessage() {
return this.service.getMessage();
}
}
#Override
public void configureApplication(ResourceConfig config) {
config.register(SimpleResource.class);
config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
}
#Before
public void before() {
assertEquals("Hello World", messageService.getMessage());
}
#Autowired
private MessageService messageService;
#Test
public void doitOnce() {
messageService.setMessage("BOOYAH");
final Response response = target("test").request().get();
assertEquals("BOOYAH", response.readEntity(String.class));
}
#Test
public void doitTwice() {
messageService.setMessage("BOOYAH");
final Response response = target("test").request().get();
assertEquals("BOOYAH", response.readEntity(String.class));
}
}
The result I would get for the second test is that the value of the service message was the default message "Hello World", even though I set the message to "BOOYAH". This tells me that there is a stale service in the application, which is not the same one being injected into the test. The first test works fine though. Without resetting, the second test would work fine also, but you are left with modified services in each test, which makes the test not self-contained.
I'm injecting my cookie param in that way (using javax.ws.rs.CookieParam)
#CookieParam("parameterCookie")
private String parameterCookie;
i have a problem to inject that parameter using Resteasy
ERROR
It is illegal to inject a #CookieParam into a singleton
That is a BaseResource and i can't modify all resources to accept that paramenter on all methods (it costs a lot). How could i inject that CookieParam in Resteasy without modify all resources?
You can work around this by injecting HttpHeaders instead:
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class CookieTest {
static final String COOKIE_NAME = "parameterCookie";
Dispatcher dispatcher;
#Before
public void setUp() throws Exception {
dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(new Resource());
}
#Test
public void name_StateUnderTest_ExpectedBehavior() throws Exception {
String cookieValue = String.valueOf(System.currentTimeMillis());
MockHttpResponse response = new MockHttpResponse();
MockHttpRequest request = MockHttpRequest.get("/")
.cookie(COOKIE_NAME, cookieValue);
dispatcher.invoke(request, response);
assertThat(response.getContentAsString(), is(COOKIE_NAME + "=" + cookieValue));
}
#Path("/")
public static class Resource {
#Context HttpHeaders headers;
#GET #Path("/")
public String getCookie(){
return headers.getCookies().get(COOKIE_NAME).toString();
}
}
}