@Test public void findAccountsByName() throws Exception { List<Account> accounts = new ArrayList<Account>(); Account accountA = new Account(); accountA.setUserId(1); accountA.setPassword("accountA"); accountA.setUserName("accountA"); accounts.add(accountA); Account accountB = new Account(); accountB.setUserId(1); accountB.setPassword("accountB"); accountB.setUserName("accountB"); accounts.add(accountB); AccountList accountList = new AccountList(accounts); when(service.findAllAccounts()).thenReturn(accountList); mockMvc .perform(get("/rest/accounts").param("name", "accountA")) .andExpect(jsonPath("$.accounts[*].userName", everyItem(endsWith("accountA")))) .andExpect(status().isOk()); }
@Test public void getExistingAccount() throws Exception { Account foundAccount = new Account(); foundAccount.setUserId(1); foundAccount.setPassword("test"); foundAccount.setUserName("test"); when(service.findAccount(1)).thenReturn(foundAccount); mockMvc .perform(get("/rest/accounts/1")) .andDo(print()) // .andExpect(jsonPath("$.password").doesNotExist()) .andExpect(jsonPath("$.userName", is(foundAccount.getUserName()))) .andExpect(status().isOk()); }
@Test public void createAccountExistingUsername() throws Exception { Account createdAccount = new Account(); createdAccount.setUserId(1); createdAccount.setPassword("test"); createdAccount.setUserName("test"); when(service.createAccount(any(Account.class))).thenThrow(new AccountExistsException()); mockMvc .perform( post("/rest/accounts") .content("{\"userName\":\"test\",\"password\":\"test\"}") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isConflict()); }
@Test public void createAccountNonExistingUsername() throws Exception { Account createdAccount = new Account(); createdAccount.setUserId(1); createdAccount.setPassword("test"); createdAccount.setUserName("test"); when(service.createAccount(any(Account.class))).thenReturn(createdAccount); mockMvc .perform( post("/rest/accounts") .content("{\"userName\":\"test\",\"password\":\"test\"}") .contentType(MediaType.APPLICATION_JSON)) .andExpect(header().string("Location", endsWith("/rest/accounts/1"))) .andExpect(jsonPath("$.userName", is(createdAccount.getUserName()))) .andExpect(status().isCreated()); verify(service).createAccount(accountCaptor.capture()); String password = accountCaptor.getValue().getPassword(); BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); assertTrue(passwordEncoder.matches("test", password)); }