首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Spring单元测试,内嵌RESTEasy服务的兑现

2012-09-27 
Spring单元测试,内嵌RESTEasy服务的实现RESTEasy介绍RESTEasy是JBoss的一个开源项目,提供各种框架帮助你构

Spring单元测试,内嵌RESTEasy服务的实现

RESTEasy介绍

RESTEasy是JBoss的一个开源项目,提供各种框架帮助你构建RESTful Web Services和RESTful Java应用程序。它是JAX-RS规范的一个完整实现并通过JCP认证。作为一个JBOSS的项目,它当然能和JBOSS应用服务器很好地集成在一起。但是,它也能在任何运行JDK5或以上版本的Servlet容器中运行。RESTEasy还提供一个RESTEasy JAX-RS客户端调用框架。能够很方便与EJB、Seam、Guice、Spring和Spring MVC集成使用。支持在客户端与服务器端自动实现GZIP解压缩。

在前面的文章介绍的基础上,实现SpringJUnit4ClassRunner

package com.jje.common.test;import java.lang.annotation.Annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.util.Collections;import java.util.List;import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer;import org.junit.runner.notification.RunNotifier;import org.junit.runners.model.InitializationError;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;public class ResteasyEmbededServer extends SpringJUnit4ClassRunner {    private TJWSEmbeddedJaxrsServer server = new TJWSEmbeddedJaxrsServer();    public ResteasyEmbededServer(Class<?> clazz) throws InitializationError {        super(clazz);    }    @Override    public void run(RunNotifier notifier) {        int port = findAnnotationValueByClass(Port.class).value();        Class[] resourceClasses = findAnnotationValueByClass(Resources.class).value();        startServer(port, resourceClasses);        try {            super.run(notifier);        } finally {            server.stop();        }    }    private void startServer(int port, Class[] resourceClasses) {        server.setPort(port);        List<Class> actualResourceClasses = server.getDeployment().getActualResourceClasses();        Collections.addAll(actualResourceClasses, resourceClasses);        server.start();    }    private <T> T findAnnotationValueByClass(Class<T> annotationClass) {        for (Annotation annotation : getTestClass().getAnnotations()) {            if (annotation.annotationType().equals(annotationClass)) {                return (T) annotation;            }        }        throw new IllegalStateException(String.format("Can't find %s on test class: %s", annotationClass, getTestClass()));    }    @Retention(RetentionPolicy.RUNTIME)    @Target(ElementType.TYPE)    public static @interface Resources {        public Class[] value();    }    @Retention(RetentionPolicy.RUNTIME)    @Target(ElementType.TYPE)    public static @interface Port {        public int value();    }}

TJWSEmbeddedJaxrsServer是RESTEasy框架提供的嵌入式服务

待续




热点排行