我已将接口声明为@RestController
的属性。该界面只有几个字段/设置程序/获取程序。
RestController和GetMapping的实现如下所示:
@RestController
@EnableAutoConfiguration
public class AccountController {
private AccountStoreInterface store;
@GetMapping(value="/account")
public Account readAccount(@RequestParam("id") String id) throws AccountNotFoundException {
Account a = store.getAccount(id);
if (a.getId().isEmpty()) {
throw new AccountNotFoundException();
}
return a;
}
@ExceptionHandler(AccountNotFoundException.class)
@ResponseStatus(NOT_FOUND)
public @ResponseBody String handleAccountNotFoundException(AccountNotFoundException ex) {
return ex.getMessage(); }
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(INTERNAL_SERVER_ERROR)
public @ResponseBody String handleNullPointerException(NullPointerException ex) {
return ex.getMessage();
}
}
接口声明如下:
public interface AccountStoreInterface {
public Account getAccount(String id) throws AccountNotFoundException;
public Account setAccount(String id, Account account) throws AccountConflictException;
}
我想使用spring-boot-starter-test
和junit4
对此进行测试。我希望以下测试返回500,因为我尚未通过实现我的接口的任何存储对象,因此它应该引发NullPointerException
。
如何配置单元测试以测试500
和404
状态码?
现在,下面的测试实际上失败了,因为返回的状态是200,我不知道junit如何到达。
@RunWith(SpringRunner.class)
@WebMvcTest(AccountController.class)
public class TestAccountController {
@Autowired private MockMvc mockMvc;
@Autowired private WebApplicationContext wac;
@MockBean
private AccountController accountController;
@Test
public void testGetAccountNotFound() throws Exception {
mockMvc.perform(get("/account?id={id}", "test-account-id-123")
.accept(APPLICATION_JSON)
.characterEncoding("UTF-8"))
.andDo(print())
.andExpect(status().isNotFound());
}
}