gpt4 book ai didi

java - 如何编写依赖于索引页的 junit 测试?

转载 作者:太空宇宙 更新时间:2023-11-04 11:45:57 25 4
gpt4 key购买 nike

我有一个应用程序,使用 java、thymeleaf 和 springboot。在主页 localhost:8080 用户必须输入一个值才能重定向到第二页“localhost:8080/getValues”

如何编写 junit 测试以便测试预期值?目前,我的测试出现 404 页面未找到,因为它取决于用户在主页上输入的值。

测试

@Test
public void test() throws Exception {

this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("index"))
.andDo(print());
//test passes
}

@Test
public void testVals() throws Exception {

this.mockMvc.perform(post("getValues"))
.andExpect(status().isNotFound()) //passes
.andExpect(model().attributeExists("webHist")); //fails //no modelandviewfound

}

Controller

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(Locale locale) throws MalformedURLException {
ModelAndView model = new ModelAndView("index");

return model;
}

@RequestMapping(value = "/getValues", method = RequestMethod.POST)
public ModelAndView getValues(Info info) throws MalformedURLException {

ModelAndView model = new ModelAndView("getValues");
model.addObject("userID", info.userID());

Customer custinfo = index.readXML(info.userID());
model.addObject("custinfo", custinfo);

model.addObject("webHist", Web_HistoryRepo.getAll(info.userID()));

return model;
}

最佳答案

关于单元测试,您没有发送信息信息您的单元中缺少 content() ,它应该类似于

 this.mockMvc.perform(post("getValues"))
.contentType(MediaType.APPLICATION_JSON)
.content(INFO_IN_JSON_FORM)
.andExpect(status().isNotFound()) //passes
.andExpect(model().attributeExists("webHist"));

如果仍然不起作用,请将 .andDo(print()) 添加到测试末尾,以便您收到有关结果的更多详细信息。

接下来我不知道你的整个Controller是什么样子,如果它用@RestController注释,如果没有你应该将@RequestBody添加到getValues()方法,以便Info将从Json映射。

如果涉及到 SPA,您不会返回 ModelAndView,而是返回 Json 响应,并且您的前端会解释它。

关于java - 如何编写依赖于索引页的 junit 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42353510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com