Pure JerseyTest不让Spring搞乱服务

时间:2015-11-16 23:16:12

标签: spring unit-testing mocking jersey-test-framework

我在使用JerseyTest和Spring时遇到了困难。以前在非Spring Java项目中,我通常为REST API做的是从JerseyTest扩展我的Test,模拟Service类并简单地(单元)测试我的REST API。现在我在我的项目中使用spring,在我的REST资源类中,使用@Autowired注释服务。现在我正在使用相同的场景。 Spring跳进来并唠叨像缺少applicationcontext.xml这样的东西。我确实想在我的制作中使用spring,但是对于我的单元测试,我不需要我的测试知道关于Spring及其所有自动装配和类路径注释处理的任何信息!我怎样才能做到这一点?这些类看起来像这样:

public class RESTResource{
  @Autowired
  MyService service;

  @GET
  public Response getSomeStuff(){
    ...
    service.getStuff()
  }

}

这是测试类

public class RESTResourceTest extends JerseyTest{

   private Service service;
   @Override
   public Application configure(){
      RESTResource resource = new RESTResource();
      service = Mockito.mock(Service.class);
      resource.setService(service);
      ResourceConfig config = new ResourceConfig();

      config.register(resource);
      return config;
   }
}

这是堆栈跟踪:

org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:252)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:538)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
    at org.glassfish.jersey.server.spring.SpringComponentProvider.createXmlSpringConfiguration(SpringComponentProvider.java:173)
    at org.glassfish.jersey.server.spring.SpringComponentProvider.createSpringContext(SpringComponentProvider.java:164)
    at org.glassfish.jersey.server.spring.SpringComponentProvider.initialize(SpringComponentProvider.java:99)
    at org.glassfish.jersey.server.ApplicationHandler$4.get(ApplicationHandler.java:408)
    at org.glassfish.jersey.server.ApplicationHandler$4.get(ApplicationHandler.java:399)
    at org.glassfish.jersey.internal.util.collection.Values$LazyValueImpl.get(Values.java:340)
    at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:350)
    at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:347)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255)
    at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:347)
    at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:299)
    at org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer.<init>(InMemoryTestContainerFactory.java:77)
    at org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer.<init>(InMemoryTestContainerFactory.java:63)
    at org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory.create(InMemoryTestContainerFactory.java:111)
    at org.glassfish.jersey.test.JerseyTest.createTestContainer(JerseyTest.java:277)
    at org.glassfish.jersey.test.JerseyTest.setUp(JerseyTest.java:609)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
    ... 56 more

P.S。我使用弹簧靴。

3 个答案:

答案 0 :(得分:1)

您可以做的是使用用于测试阶段的sure-fire插件简单地排除jersey-spring3。

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <classpathDependencyExcludes>
                        <classpathDependencyExclude>
                            org.glassfish.jersey.ext:jersey-spring3
                        </classpathDependencyExclude>
                    </classpathDependencyExcludes>
                </configuration>
            </plugin> 

答案 1 :(得分:0)

以下是一些可能对您的案例有帮助的代码段: 选项1.您的REST资源类:

@Component
@Path("/api/helloworld")
public class RESTResource{
@Autowired
MyService service;

@GET
@Produces(MediaType.TEXT_PLAIN)
public String helloMessage() {
    return "Hello World Jersey Way!";
}

}
  1. 您的测试配置类:

    @Component
    public class JerseyConfig extends ResourceConfig {
    
    /**
     * In constructor we can define Jersey Resources &amp; Other Components
    */
    public JerseyConfig() {
        register(RESTResource.class);
    }
    }
    
  2. 3.您的测试基类:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = Application.class)//NOTE : Application is a spring boot main class,or if you have specific configuration class similar to test config class above use @ContextConfiguration(classes = MyServiceSpringConfig.class) 
    public class RESTResourceTest extends JerseyTest {
    
    @Override
    protected Application configure() {
        return new JerseyConfig();
    }
    
    @Test
    public void contextLoads() {
    }
    
    @Test
    public void someTest() throws Exception {
        // Very useful test
    }
    
    
    }
    

    选项2:

    @Priority(value = 1)
    public class MySpringWebInitializer implements WebApplicationInitializer
    {
        @Override
        public void onStartup(ServletContext container)
        {
            //Tell jersey-spring3 the context is already initialized
            container.setInitParameter("contextConfigLocation", "NOTNULL");
            AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
            appContext.register(RESTResource.class);
            container.addListener(new ContextLoaderListener(appContext));
        }
    }
    

    此外,对于spring boot,您可以使用活动配置文件或配置名称运行测试用例,使用-Dspring.config.name = test传递运行时VM args以运行测试用例等。

    希望得到这个帮助,其余的是自我解释。

答案 2 :(得分:0)

The better way to integrate JerseyTest with Spring
  • 在junit测试类
  • 中没有来自JerseyTest的继承
  • 在junit测试类中没有依赖于Jersey,只是纯粹的jax-rs依赖
  • 完美地集成了SpringJUnit4ClassRunner和@ContextConfiguration

我的解决方案托管在github上。希望对你有所帮助。