Java 如何将bean加载到测试上下文中?

Java 如何将bean加载到测试上下文中?,java,spring,spring-boot,Java,Spring,Spring Boot,我有需要测试的REST服务。该服务具有spring安全认证,我需要在测试或模拟中关闭它。我决定嘲笑它,因为我无法关闭它。我为此编写了@TestConfiguration,但现在我的上下文没有加载: @TestConfiguration public class TestConfig { } @WebMvcTest(controller = MyController.class) @ContextConfiguration(classes = TestConfig.class) public M

我有需要测试的REST服务。该服务具有spring安全认证,我需要在测试或模拟中关闭它。我决定嘲笑它,因为我无法关闭它。我为此编写了
@TestConfiguration
,但现在我的上下文没有加载:

@TestConfiguration
public class TestConfig {
}

@WebMvcTest(controller = MyController.class)
@ContextConfiguration(classes = TestConfig.class)
public MyControllerTest {
    @Test
    public void simpleTest() {
    }
}
在我的主要源代码中,我有一些配置类加载了一些其他bean,而it类在我的测试中没有加载,我有一个异常:

java.lang.IllegalStateException: Failed to load ApplicationContext

我做错了什么?有人能帮我吗?我正在使用
SpringBoot 2.2.0
,在该版本中
@WebMvcTest(secure=false)
由于
安全属性不再存在而无法工作。

您可以尝试覆盖测试类中的安全配置:

@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() {
    }
}

也可以在这里查看一下:

您是否使用基于XML的注释配置?@Lakshman否,我使用基于注释的配置这是可以做到的,尝试在src\test\resource中创建1 test-applicatio.properties添加以下属性以跳过安全性security.basic.enabled=false management.security.enabled=false,您可以使用@ContextConfiguration(locations={})导入属性文件为什么不能使用yaml/properties文件关闭安全性?请参阅@Ermintar我不使用基本的HTTP身份验证,我使用自定义身份验证提供程序,这种方法对我不适用。