Spring上下文不会在单元测试中加载我的类

时间:2019-11-26 18:01:20

标签: spring junit springrunner context-configuration

我无法通过单元测试来加载配置类。

我的测试课带有注释:

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles(profiles = "test")
@ContextConfiguration (classes = ClientConfiguration.class)
public class ClientConfigurationTest { ...

ClientConfiguration.class

@ConditionalOnProperty(value = "dirt.security.oauth2client", matchIfMissing = false)
@Configuration
@PropertySource(value = "classpath:oauth2client-${spring.profiles.active:local}.properties", ignoreResourceNotFound=true)
public class ClientConfiguration {

    static {
        SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
    }

    @Bean
    @ConfigurationProperties(prefix = "dirt.security.oauth2client.client")
    ClientCredentialsResourceDetails clientConfig() {
        return new ClientCredentialsResourceDetails() {
            @Override
            public String toString() {
                return ReflectionToStringBuilder.toString(this);
            }
        };
    }

    @Bean
    @ConfigurationProperties(prefix = "dirt")
    protected DirtClientConfig dirtClientConfig() {
        return new DirtClientConfig();
    }

    @Bean
    DirtRestTemplate restTemplate() {

        DirtRestTemplate dirtRestTemplate =
                new DirtRestTemplate(clientConfig(),
                        new DefaultOAuth2ClientContext(), dirtClientConfig());
        dirtRestTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
        return dirtRestTemplate;
    }
}

这3个bean中没有一个被实例化,当我调用它时,它在其他一个bean上得到了依赖错误

@Test
public void clientConfig() {
    DirtRestTemplate results =
            (DirtRestTemplate)context
                    .getAutowireCapableBeanFactory()
                    .createBean(DirtRestTemplate.class,
                            AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE,
                            true);
    assertNotNull(results);
}

0 个答案:

没有答案