[英]How to write unit test for Controller with multiple modelattribute
我正在嘗試為我的控制器編寫單元測試,但是我需要幫助,在我的控制器之外有兩個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";
}
我相信本文可以為您提供幫助。
測試類上的@WebMvcTest
批注告訴spring不要顯示所有應用程序的詳細信息,而只顯示與API相關的信息(對於您的Controller
。 此外,它為您提供了一個方便的工具MockMvc
類,您可以使用該類來“ 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")));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.