【问题标题】:Unit testing Spring REST Controller单元测试 Spring REST 控制器
【发布时间】: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); ?

标签: spring junit


【解决方案1】:

您可能想在How to test this method with spring boot test?查看我的答案

您不仅会找到单元测试控制器的答案,还会找到如何在测试中包含过滤器、处理程序和拦截器的答案。

希望对你有帮助,

杰克

【讨论】:

    【解决方案2】:

    我认为您首先需要使用 when 子句。

      when(accountController.createAccount(account, "", uriBuilder)).then(createAccount); 
      ResponseEntity<?> createdAccount = accountController.createAccount(account, "", uriBuilder);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2012-05-25
      • 1970-01-01
      • 2016-11-14
      • 2016-01-31
      • 1970-01-01
      • 2016-02-08
      相关资源
      最近更新 更多