我有一个类似于这个的简单注释控制器:
@RequestMapping(value = { "/search" }, method = RequestMethod.POST)
public String searchForm(@Valid Account account, ModelMap model, HttpServletRequest request) {
//do something
return "app";
}
我希望用这样的单元测试来测试它:
private List<Account> listAccount = new ArrayList<Account>();
@Before
public void prepairUp() {
// //// // ===============SETUP FOR MOCK========================
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
@Test
public void tesControllerSearchForm() throws Exception {
ModelMap modelMap = mock(ModelMap.class);
Account account = mock(Account.class);
HttpServletRequest request = mock(HttpServletRequest.class);
final String review = accountController.searchForm(account, modelMap , request);
when(accountService.findAllAccount()).thenReturn(listAccount);
mockMvc.perform(MockMvcRequestBuilders.post("/search")).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.model().attribute("listAccounts", listAccount))
.andExpect(MockMvcResultMatchers.view().name(review));
}
它不起作用,没有失败,不是真的,错误行
final String review = accountController.searchForm(account, model, request);
答案 0 :(得分:1)
当您模拟控制器时,您必须手动设置通常由弹簧注入控制器的bean。这就是为什么在控制器中抛出NullPointer的原因。
修改您的准备工作以下内容:
[Some Annotations you already have...]
public class ControllerTest {
@Inject
private AccountService accountService;
@PostConstruct
public void prepairUp() {
// //// // ===============SETUP FOR MOCK========================
MockitoAnnotations.initMocks(this);
AccountController accountController = new AccountController();
ReflectionTestUtils.setField(accountController, "accountService", accountService);
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
@Test
public void tesControllerSearchForm() {
...
}
....
}
您只需要设置一次,所以只需将@Before更改为@PostConstruct即可。