我有需要测试的 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/