![](/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.