【问题标题】:How can I write a junit test to that is dependent on index page?如何编写依赖于索引页面的junit测试?
【发布时间】:2017-02-20 20:18:15
【问题描述】:

我有一个应用程序,使用 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

}

控制器

@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;
    }

【问题讨论】:

  • 你能展示一些控制器的外观代码吗?
  • @pezetem 我添加了我的控制器,你能告诉我如何将这个多页逻辑更改为 SPA 吗?我认为如果我将其更改为 SPA,它将删除依赖项

标签: java spring-boot junit


【解决方案1】:

关于单元测试,您没有发送Info info 您缺少单元中的 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注解的,如果没有,你应该在getValues()方法中添加@RequestBody,以便从Json映射Info。

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

【讨论】:

  • .content 不起作用。我尝试导入 MediaType。但出现错误。 “APPLICATION_JSON 无法解析或不是字段”导入 org.springframework.http
  • 我的控制器有@Controller的注解。如果我不使用 ModelAndView 的过程是什么?您能给我一个网址,我可以将其转换为 SPA。
  • 对于 SPA,您可以尝试使用 Angular 教程 (angular.io/docs/ts/latest/tutorial),我相信您在代码中使用 JSP,并且无法使用 SPA
  • 我正在使用 Thymeleaf、Java、Spring-boot 和 angularjs。没有 JSP。
  • 好的,那你为什么要使用 ModelAndView 呢?您应该从 angularJS 调用某个端点,并作为响应从 Spring Boot 接收 Json
猜你喜欢
  • 1970-01-01
  • 2011-02-04
  • 1970-01-01
  • 2012-03-28
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多