如何在使用OAuth时在SpringBoot应用程序中配置测试

时间:2016-04-04 16:00:09

标签: java spring-security spring-boot

我的SpringBoot应用程序使用spring注释和属性文件充当OAuth提供程序:

@SpringBootApplication
@EnableResourceServer
@EnableAuthorizationServer
public class BioDare2WSApplication {

    public static void main(String[] args) {
        SpringApplication.run(BioDare2WSApplication.class, args);
    }        
}

该应用程序正常运作。

但是当我使用SpringJUnit4ClassRunner运行测试时,除非@WebAppConfiguration注释添加到测试类中,否则它们会失败:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BioDare2WSApplication.class)
@WebAppConfiguration //needed to prevent Failed to load ApplicationContext 
public class BioDare2WSApplicationTest {

    public BioDare2WSApplicationTest() {
    }

    @Test
    public void contextLoads() {
        assertTrue(true);
    }

}

如果省略@WebAppConfiguration,则上下文加载失败:

java.lang.IllegalStateException: Failed to load ApplicationContext
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) 
    Caused by: org.springframework.beans.factory.BeanCreationException: 
    Error creating bean with name 'org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration': 
    Injection of autowired dependencies failed; 
        nested exception is org.springframework.beans.factory.BeanCreationException: 
        Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setObjectPostProcessor(org.springframework.security.config.annotation.ObjectPostProcessor); 
        nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.ObjectPostProcessor] ...

我如何手动配置WebSecurityConfigurerAdapter,因此我不必将WebSecurityConfigurerAdapter置于我的所有测试类之上。

我想测试"配置"我可以在测试期间使用的类(例如设置测试数据库等),如:

public class BioDare2TestConfiguration extends BioDare2WSApplication {
...
  HOW TO CONFIGURE IT SO not to have oauth exceptions
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BioDare2TestConfiguration.class)
public class BioDare2WSApplicationTest {
...
}

在BioDare2TestConfiguration之上添加@WebAppConfiguration无济于事。这样的注释必须在测试类本身上起作用。

0 个答案:

没有答案