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

标签 java spring spring-boot

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

@TestConfiguration
public class TestConfig {
}

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

在我的主要源代码中,我有一些配置类加载其他一些bean,但它的类在我的测试中没有加载,并且我有一个异常(exception):

java.lang.IllegalStateException: Failed to load ApplicationContext

我做错了什么?谁能帮我?我使用 SpringBoot 2.2.0 ,在该版本中 @WebMvcTest(secure = false) 无法工作,因为 secure 属性不再存在。

最佳答案

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

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

也可以在这里看看:https://howtodoinjava.com/spring-boot2/testing/springboot-test-configuration/

关于java - 如何将 bean 加载到测试上下文中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59320864/

相关文章:

java - 将两个字符串编码/解码为一个字符串,然后再还原为两个字符串

java - android.os.BinderProxy 无法转换为 org.eclipse.paho.android.service.MqttServiceBinder

Spring Boot 应用程序在主方法中从属性文件中读取值

java - LocalDateTime 将无效日期解析为有效日期并且不抛出任何异常

JavaFX WebView 不加载页面

java - 使用 HashMap 迭代器

java - JHipster UserService - 变量可能尚未初始化

java - JBoss 7.1 - 声明数据源并通过 JNDI 访问

java - 模拟 bean 的依赖项的 NoSuchBeanDefinitionException

java - 将 Amazon IonStruct 转换为 JSONPObject