開發與維運

Java單元測試之 Apache CXF Restful

Apache CXF框架的單元測試需要內置Jetty容器

<dependency>
   <groupId>org.eclipse.jetty</groupId>
   <artifactId>jetty-webapp</artifactId>
   <version>${jetty.version}</version>
   <scope>test</scope>
</dependency>

下面是一個基於Spring框架的Apache CXF測試示例

applicationContext-restful.xml

<import resource="classpath:META-INF/cxf/cxf.xml" />
 
<context:component-scan base-package="com.faw_qm.cloud.platform.*.restful" />
 
<jaxrs:server id="demoServer" address="/">
   <jaxrs:serviceBeans>
      <ref bean="demoRestful" />
   </jaxrs:serviceBeans>
   <jaxrs:providers>
      <bean class="com.alibaba.fastjson.support.jaxrs.FastJsonProvider" />
   </jaxrs:providers>
   <jaxrs:extensionMappings>
      <entry key="json" value="application/json" />
   </jaxrs:extensionMappings>
</jaxrs:server>

DemoRestful.java

@Path("demo")
@Component("demoRestful")
public class DemoRestful {
 
    @POST
    @Path("/test")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String test(String str) {
 
        return "This is a cxf restful test method.";
    }
}

DemoRestfulTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = Application.class)
public class DemoRestfulTest {
 
    public final String REST_SERVICE_URL = "http://localhost:8088/rest";
 
    public final Server server = new Server(8088);
 
    @Before
    public void before() {
        // Register and map the dispatcher servlet
        final ServletHolder servletHolder = new ServletHolder(new CXFServlet());
        final ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        context.addServlet(servletHolder, "/rest/*");
        context.addEventListener(new ContextLoaderListener());
        context.setInitParameter(
                "contextConfigLocation",
                "classpath*:/applicationContext-restful.xml");
        server.setHandler(context);
        try {
            server.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @After
    public void after() {
        try {
            server.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Test
    public void test() throws Exception {
 
        JSONObject json = new JSONObject();
  
        json.put("name", "test");
 
        WebClient client = WebClient.create(REST_SERVICE_URL);
 
        Response response = client.path("/demo/test")
                    .accept("application/json")
                    .type("application/json; charset=UTF-8")
                    .post(json.toJSONString());
 
        Assert.assertEquals(response.getStatus(), 200);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *