Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CxfServerTestRule
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.feature.LoggingFeature;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
import org.junit.rules.ExternalResource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* ClassRule for unit testing transport layer. Creates local server for testing client behaviour
*/
public class CxfServerTestRule<T> extends ExternalResource {
private final T resource;
private final String endpoint;
private Server server;
public CxfServerTestRule(final T resource, final String endpoint) {
this.resource = resource;
this.endpoint = endpoint;
}
@Override
protected void before() throws Throwable {
super.before();
final Class<?> serviceInterface = this.resource.getClass();
final JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(serviceInterface);
final List<Object> providers = new ArrayList<>();
providers.add(new org.apache.cxf.jaxrs.provider.JAXBElementProvider());
providers.add(new JacksonJaxbJsonProvider());
sf.setProviders(providers);
sf.setFeatures(Collections.singletonList(new LoggingFeature()));
sf.setResourceProvider(serviceInterface,
new SingletonResourceProvider(this.resource, true));
sf.setAddress(endpoint);
server = sf.create();
}
@Override
protected void after() {
super.after();
server.destroy();
}
public T getResource() {
return resource;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment