Spring|Spring MVC Test with Mockito

MockMvc VetController

@Controller public class VetController {private final ClinicService clinicService; @Autowired public VetController(ClinicService clinicService) { this.clinicService = clinicService; }@RequestMapping(value = https://www.it610.com/article/{"/vets.html"}) public String showVetList(Map model) { // Here we are returning an object of type 'Vets' rather than a collection of Vet objects // so it is simpler for Object-Xml mapping Vets vets = new Vets(); vets.getVetList().addAll(this.clinicService.findVets()); model.put("vets", vets); return "vets/vetList"; } }

VetControllerTest
@ExtendWith(MockitoExtension.class) class VetControllerTest {@Mock ClinicService clinicService; @Mock Map model; @InjectMocks VetController controller; List vetsList = new ArrayList<>(); MockMvc mockMvc; @BeforeEach void setUp() { vetsList.add(new Vet()); given(clinicService.findVets()).willReturn(vetsList); mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); }@Test void testControllerShowVetList() throws Exception { mockMvc.perform(get("/vets.html")) .andExpect(status().isOk()) .andExpect(model().attributeExists("vets")) .andExpect(view().name("vets/vetList")); } }

    推荐阅读