【问题标题】:Should I create 2 unit tests for this specific method? Spring MVC app我应该为此特定方法创建 2 个单元测试吗? Spring MVC 应用程序
【发布时间】:2018-03-19 18:52:02
【问题描述】:

方法代码如下:

@RequestMapping("/employee/{id}")
public String showSpecificEmployee(@PathVariable String id, 
@RequestParam(name = "date", required = false) String date, Model model){

    if(date == null)
        date = YearMonth.now().toString();

    model.addAttribute("employee", employeeService.findEmployeeWithFilteredWorkdaysAndPayments(new Long(id), date));

    return "specificEmployee";
}

到目前为止,我已经创建了一个测试:

@Test
public void showSpecificEmployee() throws Exception {

    //given
    Employee employee = new Employee();

    //when
    when(employeeService.findEmployeeWithFilteredWorkdaysAndPayments(anyLong(), anyString())).thenReturn(employee);

    //then
    mockMvc.perform(get("/employee/1"))
            .andExpect(status().isOk())
            .andExpect(view().name("specificEmployee"))
            .andExpect(model().attributeExists("employee"));

    verify(employeeService, times(1)).findEmployeeWithFilteredWorkdaysAndPayments(anyLong(), anyString());
}

这样好吗?或者我应该再写一个来检查date 是否创建正确?非常感谢任何其他建议。

【问题讨论】:

  • 是的,你应该这样做。

标签: java spring unit-testing spring-mvc junit


【解决方案1】:

是的,您应该创建 2 个测试用例。 一种情况是非空日期,另一种情况是空日期。
如果你用 jacoco 之类的东西检查你的测试覆盖率,你可以直观地看到两个案例之间有什么不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多