简体   繁体   中英

How to load beans into test context?

I have the REST service that I need to testing. That service has a spring security authentication and I need to turn off it in my tests or mock. I decided to mock it because I couldn't turn off it. I write @TestConfiguration for that but now my context not load:

@TestConfiguration
public class TestConfig {
}

@WebMvcTest(controller = MyController.class)
@ContextConfiguration(classes = TestConfig.class)
public MyControllerTest {
    @Test
    public void simpleTest() {
    }
}

and in my main source, I have some config class that load some other beans and it class did not load in my test and I have an exception:

java.lang.IllegalStateException: Failed to load ApplicationContext

What I do wrong? Can anyone help me? I using SpringBoot 2.2.0 and in that version @WebMvcTest(secure = false) not working because of secure property doesn't exist anymore.

You could try overriding the security configuration in your test class:

@WebMvcTest(controller = MyController.class)
public MyControllerTest {

    @Configuration
    public class MyTestsSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //...
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //...
        }
    }

    @Test
    public void simpleTest() {
    }
}

Also have a look at this here: https://howtodoinjava.com/spring-boot2/testing/springboot-test-configuration/

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