0

I can't get my unit test to load my configuration class.

My test class is annotated:

@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;
    }
}

None of the 3 beans get instantiated, and when I call this, it gets a dependecy error on one of the other beans

@Test
public void clientConfig() {
    DirtRestTemplate results =
            (DirtRestTemplate)context
                    .getAutowireCapableBeanFactory()
                    .createBean(DirtRestTemplate.class,
                            AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE,
                            true);
    assertNotNull(results);
}
ed4becky
  • 1,488
  • 1
  • 17
  • 54
  • What version of JUnit do you use? Also try replacing `@ContextConfiguration (classes = ClientConfiguration.class)` with `@Import(ClientConfiguration.class)` – Nikolai Shevchenko Nov 26 '19 at 18:55
  • JUnit 4. @IMport made no difference – ed4becky Nov 26 '19 at 19:41
  • I cannot reproduce your environment 1:1 but when trying to mimic it, I get failures when ```@ConditionalOnProperty``` is present. Can you quickly check whether your beans are created when the conditional is removed - just to be sure that you're not chasing ghosts. – Dirk Bolte Nov 26 '19 at 20:13
  • Thanks for the suggestion. It did not, however, change my results – ed4becky Nov 27 '19 at 14:22

0 Answers0