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

Posted

技术标签:

【中文标题】如何将 bean 加载到测试上下文中?【英文标题】:How to load beans into test context? 【发布时间】:2020-04-06 19:20:14 【问题描述】:

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

@TestConfiguration
public class TestConfig 


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

在我的主要来源中,我有一些加载其他 bean 的配置类,它的类在我的测试中没有加载,我有一个异常:

java.lang.IllegalStateException: Failed to load ApplicationContext

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

【问题讨论】:

您是否使用基于 XML 的注释配置? @Lakshman 不,我使用基于注释的配置 可以,试试这个 Create 1 test-applicio.properties in src\test\resource 添加下面的属性来跳过安全 security.basic.enabled=false management.security.enabled=false 和你可以使用@ContextConfiguration(locations =) 导入属性文件 为什么不能使用 yaml/properties 文件关闭安全性?见***.com/questions/23894010/… @Ermintar 我不使用基本的 HTTP 身份验证,我使用自定义身份验证提供程序,这种方法不适合我。 【参考方案1】:

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

@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/

【讨论】:

以上是关于如何将 bean 加载到测试上下文中?的主要内容,如果未能解决你的问题,请参考以下文章

如何推迟调用@PostConstruct,直到jUnit设置测试上下文

可以在加载的 Spring 上下文中以编程方式替换 Spring Bean

Spring Boot JPA 测试 bean 不在上下文中

使用@SpringBootTest时如何在测试类中自动装配bean

如何将 Java-config 类导入 XML-config 以便两个上下文都有 bean?

如何使用 Spring 重新加载属性?