所以我正在尝试测试我写的Spring启动MVC应用程序:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = PetClinicApplication.class)
@WebAppConfiguration
public class OwnerControllerTests {
@Mock
private OwnerService ownerService;
@InjectMocks
private OwnerController ownerController;
private MockMvc mockMvc;
public void setup(){
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(ownerController).build();
}
@Test
public void testOwnerList() throws Exception{
List<Owner> owners = new ArrayList<>();
owners.add(new Owner());
owners.add(new Owner());
when(ownerService.getAll()).thenReturn((List<Owner>) owners);
mockMvc.perform(get("/ownerList"))
.andExpect(status().isOk())
.andExpect(view().name("ownerList"))
.andExpect(model().attribute("ownerList", List.class));
}
}
我正在排队
when(ownerService.getAll()).thenReturn((List<Owner>) owners);
在调试器模式下ownerService = null 这是OwnerService.class
@Transactional
public Collection<Owner> getAll() {
return ownerDao.getAll();
}
此方法应返回Owner.class对象列表
所有者控制器代码段
@Controller
public class OwnerController {
@Autowired
private OwnerService ownerService;
@RequestMapping("/addOwner")
public String addOwner(Model model) {
model.addAttribute("Owner", new Owner());
return "addOwner";
}
@RequestMapping(value = "addOwner.do", method = RequestMethod.POST)
public String addOwnerDo(@Valid @ModelAttribute(value = "Owner") Owner owner, BindingResult result) {
if (result.hasErrors())
return "addOwner";
ObjectBinder.bind(owner);
ownerService.add(owner);
return "redirect:addOwner";
}
@RequestMapping("/ownerList")
public String ownerList(Model model) {
model.addAttribute("ownerList", ownerService.getAll());
return "ownerList";
}
@RequestMapping("/ownerList/{id}")
public String ownerDetails(@PathVariable(value = "id") int id, Model model) {
Owner owner = ownerService.get(id);
model.addAttribute("owner", owner);
return "ownerDetail";
}
// to refactor
@RequestMapping(value = "/ownerList/{id}.do")
public String ownerDetailsDo(@ModelAttribute(value = "owner") Owner owner, BindingResult result,
@RequestParam(value = "action") String action, Model model) {
switch (action) {
case "update":
ObjectBinder.bind(owner);
ownerService.update(owner);
return "ownerDetail";
case "delete":
ownerService.remove(owner.getId());
model.addAttribute("ownerList", ownerService.getAll());
return "ownerList";
}
model.addAttribute("owner", owner);
return "ownerDetail";
}
}