【发布时间】:2018-07-21 12:26:14
【问题描述】:
我尝试测试在MainController 中定义的名为loadData 的方法,它以字符串形式返回结果。尽管此方法实际上在 Web 应用程序在 servlet 容器上运行时(或在我调试代码时)返回数据,但当我从基于 JUnit 5 和 Mockito 的测试类调用它时,没有数据返回。
这是我的配置:
@ContextConfiguration(classes = {WebAppInitializer.class, AppConfig.class, WebConfig.class})
@Transactional
@WebAppConfiguration
public class TestMainController {
@InjectMocks
private MainController mainController;
private MockMvc mockMvc;
@BeforeEach
public void init() {
mockMvc = MockMvcBuilders.standaloneSetup(this.mainController).build();
}
@Test
public void testLoadData() throws Exception {
MvcResult mvcResult = mockMvc
.perform(MockMvcRequestBuilders.get("/loadData.ajax"))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
Assertions.assertNotNull(mvcResult.getResponse().getContentAsString(), "response should not be null");
}
}
由于java.lang.NullPointerException 导致测试失败,因为this.mainController 是null。
环境详情:
Spring version: 5.0.3
JUnit version: 5.0.3
mockito version: 1.9.5
hamcrest version: 1.3
json-path-assert version: 2.2.0
编辑:这里是MainController的loadData方法:
@RequestMapping(value = "/loadData.ajax", method = RequestMethod.GET)
public String loadData(HttpServletRequest request, HttpServletResponse response) {
List list = mainService.loadData(); // starts a transaction and invokes the loadData method of mainDAO repository which basically loads data from the database
return JSONArray.fromObject(list).toString();
}
【问题讨论】:
-
你不用MockHttp直接调用控制器的方法。你模拟一个 URL 的使用:docs.spring.io/spring-security/site/docs/current/reference/html/…
-
假设我要测试的 URL 是
loadData.ajax。你能指导我设置测试环境吗?通过您分享的指南尝试了以下操作,但没有运气:mockMvc.perform(get("/loadData.ajax")); -
添加您的
MainController。你的测试有什么奇怪的,你有一个 web 配置和一个常规配置,你不应该只有一个吗? -
@M.Deinum
AppConfig用于创建session factory和transaction managerbean。WebConfig实现WebMvcConfigurer并定义了所有其他必需的 bean,包括view revolvers、interceptors、tasks等。 -
在同一个测试类中不可能声明
@SpringJUnitWebConfig和@SpringJUnitConfig。 Spring 只会尊重其中的 一个,即它找到的第一个。
标签: spring spring-mvc junit mockito junit5