简体   繁体   中英

How to eliminate @Configuration classes with security enabled in Spring Boot unit testing

I am on a new microservice which is working fine and all the test cases were also working fine. Recently, the Spring Boot microservice is enabled with spring security with sso. Microservice is working fine but test cases are getting failed because of security. I have a class which needs to eliminated at run time during spring boot unit test. I provide below the code.

@Configuration
@Slf4j
public class CloudSecurityConfig {
    private String host = "some host";
    private String port = System.getenv("redis.port");
    private String password = System.getenv("redis.password");
    private String ssl = System.getenv("redis.ssl");
    
    @Bean
    JedisPoolConfig jedisPoolConfig(@Value("${redis.pool.maxactive}") int maxActive,
            @Value("${redis.pool.maxidle}") int maxIdle, @Value("${redis.pool.minidle}") int minIdle) {
        .... Other code
        return jedisPoolConfig;
    }
    
    @Bean
    JedisConnectionFactory jedisConnectionFactory() throws Exception {
            .... Other code
        
        return jedisConFactory;
    }

    @Bean
    @Primary
    public RedisTemplate<String, CtmUser> redisTemplate() throws Exception {
        .... Other code
        return redisTemplate;
    }
}

I have also tried with this link Java Spring Boot Test: How to exclude java configuration class from test context . But it is not working. I get the following error details.

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<?, ?>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1717) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1273) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
    ... 84 common frames omitted

The above is coming from the class CloudSecurityConfig . I think, if I am able to remove this configuration, everything will work fine.

The above error is followed by the below error:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customAuthenticationProvider': Unsatisfied dependency expressed through field 'template'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<?, ?>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I have tried with the following options.

//@EnableMongoRepositories
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration()
@SpringBootTest(classes = { ValidationApplication.class, TestMongoConfiguration.class })
//@ImportAutoConfiguration(classes = {ValidationApplication.class,TestMongoConfiguration.class})
//@EnableAutoConfiguration(exclude={ DataSourceAutoConfiguration.class, RedisAutoConfiguration.class,
//        RedisRepositoriesAutoConfiguration.class, MongoAutoConfiguration.class })

//@EnableAutoConfiguration(exclude={ DataSourceAutoConfiguration.class, RedisAutoConfiguration.class,
//      RedisRepositoriesAutoConfiguration.class, MongoAutoConfiguration.class, SecurityAutoConfiguration.class })

//@EnableAutoConfiguration(exclude={ CloudSecurityConfig.class })

//@TestPropertySource(inheritProperties = false, properties = 
//        "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration")
//@TestConfiguration()
//@ConditionalOnProperty(name = "test", havingValue="test")
@ActiveProfiles("test")
@ComponentScan(basePackages = {"com.a.b.c.d"}
, excludeFilters = {
    @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {SecurityCloudConfig.class})})
public class CheckTest {

    @Autowired
    private MyController controller;
    
    @Test
    void testAllBeforeEntry() {
        ResponseEntity<?> re = controller.getValdiations();
        boolean flag = re.getStatusCode().is2xxSuccessful();
        assertEquals(true, flag);
    }

}

Instead of ignoring it would be better to override the configure class. You could write the appropriate TestConfiguration classes for the test env. An example is added here:


@TestConfiguration
public class TestSecurityConfig {

    @Bean
    @Primary
    JedisPoolConfig jedisPoolConfig(@Value("${redis.pool.maxactive}") int maxActive,
            @Value("${redis.pool.maxidle}") int maxIdle, @Value("${redis.pool.minidle}") int minIdle) {
          // your test environment specific code/configuration.
    }

    @Bean
    JedisConnectionFactory jedisConnectionFactory() throws Exception {
            .... Other code
        // test environment specific code.
    }
    // .... Other configurations which needs to be override.

    

Note: Don't forget to add @Primary in test Beans and spring.main.allow-bean-definition-overriding=true in test application.properties file. And add @SpringBootTest(classes = TestSecurityConfig.class) in main unit test class to override the original Beans.

You could also supply MockBean instead of real one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM