【发布时间】:2018-05-14 17:23:43
【问题描述】:
我有一个 Spring 引导控制器,其方法如下:
// CREATE
@RequestMapping(method=RequestMethod.POST, value="/accounts")
public ResponseEntity<Account> createAccount(@RequestBody Account account,
@RequestHeader(value = "Authorization") String authorizationHeader,
UriComponentsBuilder uriBuilder) {
if (!account.getEmail().equalsIgnoreCase("")) {
account = accountService.createAccount(account);
HttpHeaders headers = new HttpHeaders();
System.out.println( "Account is null = " + (null == account)); //For debugging
headers.setLocation(uriBuilder.path("/accounts/{id}").buildAndExpand(account.getId()).toUri());
return new ResponseEntity<>(account, headers, HttpStatus.CREATED);
}
return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST);
}
我正在尝试像这样对其进行单元测试:
@Test
public void givenValidAccount_whenCreateAccount_thenSuccessed() throws Exception {
/// Arrange
AccountService accountService = mock(AccountService.class);
UriComponentsBuilder uriBuilder = mock(UriComponentsBuilder.class);
AccountController accountController = new AccountController(accountService);
Account account = new Account("someone@domain.com");
/// Act
ResponseEntity<?> createdAccount = accountController.createAccount(account, "", uriBuilder);
/// Assert
assertNotNull(createdAccount);
//assertEquals(HttpStatus.CREATED, createdAccount.getStatusCode());
}
但帐户始终为空。知道为什么吗?
【问题讨论】:
-
given(accountService.save(account)).willReturn(account);?