指定定制应用上下文

rob*_*ink 12 java spring unit-testing jersey-2.0

我们正在使用泽西弹簧3将泽西1.x的一些数据服务从泽西1.x迁移到泽西2.x.

我们有一些继承自JerseyTest的测试类.其中一些类使用未在web.xml文件中指定的自定义applicationContext.xml文件.

在Jersey 1.x中,扩展JerseyTest的测试类可以使用WebappDescriptor.Builder调用超级构造函数,可以传递上下文参数来设置或覆盖应用程序上下文路径.

例如

public MyTestClassThatExtendsJerseyTest()
{
    super(new WebAppDescriptor.Builder("com.helloworld")
    .contextParam( "contextConfigLocation", "classpath:helloContext.xml")
    .servletClass(SpringServlet.class)
    .contextListenerClass(ContextLoaderListener.class)
    .requestListenerClass(RequestContextListener.class).build());
}
Run Code Online (Sandbox Code Playgroud)

如何用Jersey 2.x实现同样的目标?

我已经梳理了API文档,用户指南和一些来源,但无法找到答案.

谢谢.

Ben*_*age 8

这对我不起作用,因为我没有使用.xml样式配置,我正在使用@Configuration注释.所以我不得不直接向ResourceConfig类提供应用程序上下文.

我在JerseyTest中定义了configure方法,如下所示:

@Override
protected Application configure() {
  ResourceConfig rc = new ResourceConfig();

  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  rc.property("contextConfig", ctx);
}
Run Code Online (Sandbox Code Playgroud)

其中SpringConfig.class是带有@Configuration注释和导入的类org.springframework.context.annotation.AnnotationConfigApplicationContext


Mic*_*dos 7

让我们假设您的Application外观如下:

@ApplicationPath("/")
public class MyApplication extends ResourceConfig {

    /**
     * Register JAX-RS application components.
     */
    public MyApplication () {
        // Register RequestContextFilter from Spring integration module. 
        register(RequestContextFilter.class);

        // Register JAX-RS root resource.
        register(JerseySpringResource.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

您的JAX-RS根资源如:

@Path("spring-hello")
public class JerseySpringResource {

    @Autowired
    private GreetingService greetingService;

    @Inject
    private DateTimeService timeService;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getHello() {
        return String.format("%s: %s", timeService.getDateTime(), greetingService.greet("World"));
    }
}
Run Code Online (Sandbox Code Playgroud)

并且您helloContext.xml可以直接从类路径中获得名为spring的spring描述符.现在,您想getHello使用Jersey Test Framework 测试您的资源方法.你可以写下你的测试:

public class JerseySpringResourceTest extends JerseyTest {

    @Override
    protected Application configure() {
        // Enable logging.
        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);

        // Create an instance of MyApplication ...
        return new MyApplication()
                // ... and pass "contextConfigLocation" property to Spring integration.
                .property("contextConfigLocation", "classpath:helloContext.xml");
    }

    @Test
    public void testJerseyResource() {
        // Make a better test method than simply outputting the result.
        System.out.println(target("spring-hello").request().get(String.class));
    }
}
Run Code Online (Sandbox Code Playgroud)