Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CXF REST Service Unit Test
package de.tracx.pkp.rest.service;
import java.io.IOException;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import de.tracx.HelloWorldResource;
public class HelloWorldResourceTest {
private static String BASE_URL = "http://localhost:9091/";
private static DefaultHttpClient client;
private static Server server;
@BeforeClass
public static void createClient() {
client = new DefaultHttpClient();
server = createServer();
}
@Test
public void testGetHelloWorld() throws IOException {
final HttpResponse response = client.execute(createHttpGet());
Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
}
private HttpGet createHttpGet() {
HttpGet httpGet = new HttpGet(BASE_URL + "hello-world");
httpGet.addHeader("Accept", "application/json");
return httpGet;
}
private static Server createServer() {
JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
factoryBean.setProvider(new JacksonJsonProvider());
factoryBean.setResourceClasses(HelloWorldResource.class);
factoryBean.setResourceProvider(new SingletonResourceProvider(new HelloWorldResource()));
factoryBean.setAddress(BASE_URL);
return factoryBean.create();
}
@AfterClass
public static void closeClient() {
client.getConnectionManager().shutdown();
server.destroy();
}
}
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${cxf.version}</version>
</dependency>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment