0

I have a Spring boot controller with a method like this:

// 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);
}

I'm trying to unit test it like this:

@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("[email protected]");

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

    /// Assert
    assertNotNull(createdAccount);
    //assertEquals(HttpStatus.CREATED, createdAccount.getStatusCode());
}

but the account is always null. Any idea why is that ?

1
  • given(accountService.save(account)).willReturn(account); ? Commented May 14, 2018 at 17:39

2 Answers 2

2

You may want to check my answer in How to test this method with spring boot test?

Not only you will find an answer to unit testing controllers but also how to include filters, handlers and interceptors in your test.

Hope this helps,

Jake

Sign up to request clarification or add additional context in comments.

Comments

0

I think you need to when clause first of all.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.