如何为具有多个模式分布的Controller编写单元测试

问题描述 投票:0回答:1

我正在尝试为我的控制器编写一个单元测试,但我需要帮助,我的控制器外面有两个modelAttribute作为枚举,用于我的所有控制器,所以这是我的代码。请帮助我,我是测试单元的新手。

@Autowired
private MaintenanceService maintenanceService;

@ModelAttribute("departments")
public List<Department> getDepartments(){
    return Arrays.asList(Department.values());
}

@ModelAttribute("servicetypes")
public List<ServiceType> getServiceTypes(){
    return Arrays.asList(ServiceType.values());
}

@GetMapping("/ListOfMaintenance")
public String showListOfMaintenancePage(Model model) {
    model.addAttribute("maintenance",new Maintenance());
    model.addAttribute("Maintenances",maintenanceService.retriveListOfMaintenance());
    return "List_Of_Maintenance";
}
java spring unit-testing spring-boot
1个回答
0
投票

我相信this article可以帮助你。

测试类上的@WebMvcTest注释告诉spring不要提出所有应用程序的详细信息,而只提供与API相关的那些,在你的情况下你的Controllers。此外,它还为您提供了一个方便的工具 - MockMvc类,您可以使用它来向控制器“发送”请求,就好像它们是实际的HTTP调用一样。您还可以断言这些调用的输出,以验证您希望控制器应该执行的操作实际上是什么。看一看:

@RunWith(SpringRunner.class)
@WebMvcTest
public class WebLayerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnDefaultMessage() throws Exception {
        this.mockMvc.perform(get("/"))
                    .andDo(print())
                    .andExpect(status().isOk())
                    .andExpect(content().string(containsString("Hello World")));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.