![](/img/trans.png)
[英]SpringJUnit4ClassRunner does not close the Application Context at the end of JUnit test case
[英]SpringJUnit4ClassRunner does not see my in context defined in java config
我正在尝试测试我的春季安全表格。 我的项目中有完整的注释配置(请看下面)。 现在,我尝试通过SpringJUnit4ClassRunner设置一个测试用例,并检查其中的一些条件。 我无法执行此操作,因为@ContextConfiguration批注看不到我的上下文配置。 我使用AbstractAnnotationConfigDispatcherServletInitializer来配置我的项目。 另请参见下面的代码。
这是测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebInit.class)
public class test {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
public void someTest() throws Exception {
mockMvc.perform(post("/").with(csrf().asHeader()).with(user("testuser").roles("USER")));
}
}
这是配置类:
@Configuration
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class, SecurityConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
而且我附上错误日志
严重:在允许TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@4157f54e]准备测试实例[securityTests.test@7fa98a66] org.springframework.beans.factory.BeanCreationException时捕获异常:创建名称为'securityTests的bean时出错.test':自动连接的依赖项注入失败; 嵌套的异常是org.springframework.beans.factory.BeanCreationException:无法自动连线字段:私有org.springframework.web.context.WebApplicationContext securityTests.test.context; 嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有找到类型为[org.springframework.web.context.WebApplicationContext]的合格Bean:需要至少1个符合此依赖条件的自动装配候选bean。 依赖项注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}
我所有的spring依赖项在pom.xml中都有相同的版本(spring 4.2.3.RELEASE)。 我不想创建将为我配置上下文的.xml文件。 我希望所有工作都在Java配置中完成。 我该怎么做? 预先感谢您的帮助
添加一个@WebAppConfiguration
以便WebApplicationContext
可用。
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = WebInit.class)
public class test {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
public void someTest() throws Exception {
mockMvc.perform(post("/").with(csrf().asHeader()).with(user("testuser").roles("USER")));
}
}
我实际上自己解决了我的问题。 事实证明,在我的pom.xml文件中,我依赖于spring数据2.0.1.RELEASE,从而以某种方式中断了测试的正确运行。 最可能的原因是spring数据2.0.1从其他我添加到pom.xml的spring组件中拉出了一些类,但是我的是4.2.1.RELEASE版本,而spring数据是5.0.0.RELEASE。 因此发生了覆盖。 无论如何,从pom.xml删除spring数据依赖关系后,一切都进行得很好。 谢谢答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.