[英]Running tests with Spring Boot
所以我試圖測試我編寫的Spring boot 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";
}
}
您忘了使用@Before
注釋設置方法,以使@Before
不創建和注入@Before
,請嘗試以下操作:
@Before
public void setup(){
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.