0

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.

John
  • 1,375
  • 4
  • 17
  • 40
  • Are you using XML based configuration of annotation? – Lakshman Dec 13 '19 at 11:22
  • @Lakshman no, I using annotation-based configuration – John Dec 13 '19 at 11:47
  • It can be done, try this Create 1 test-applicatio.properties in src\test\resource add below properties to skip security security.basic.enabled=false management.security.enabled=false and you can use @ContextConfiguration(locations ={}) to import property file – Lakshman Dec 13 '19 at 13:26
  • Why couldn't you turn security off using yaml/properties file? See https://stackoverflow.com/questions/23894010/spring-boot-security-disable-security – Ermintar Dec 13 '19 at 14:04
  • @Ermintar I don't use basic HTTP authentication, I use a custom authentication provider and this approach not works for me. – John Dec 13 '19 at 14:38

1 Answers1

0

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/