com.tamnd.app.rest.mvc.AccountControllerTest.java Source code

Java tutorial

Introduction

Here is the source code for com.tamnd.app.rest.mvc.AccountControllerTest.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tamnd.app.rest.mvc;

import com.tamnd.app.core.entities.Account;
import com.tamnd.app.core.services.AccountService;
import com.tamnd.app.core.services.exceptions.AccountExistsException;
import com.tamnd.app.core.services.util.AccountList;
import com.tamnd.app.rest.controller.AccountController;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.ArgumentCaptor;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.verify;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 *
 * @author tamnd2
 */
public class AccountControllerTest {

    @InjectMocks
    private AccountController controller;
    @Mock
    private AccountService service;
    private MockMvc mockMvc;
    private ArgumentCaptor<Account> accountCaptor;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        accountCaptor = ArgumentCaptor.forClass(Account.class);
    }

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

    @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 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 getNonExistingAccount() throws Exception {
        when(service.findAccount(1)).thenReturn(null);

        mockMvc.perform(get("/rest/accounts/1")).andExpect(status().isNotFound());
    }

    @Test
    public void findAllAccounts() 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"))
                .andExpect(jsonPath("$.accounts[*].userName", hasItems(endsWith("accountA"), endsWith("accountB"))))
                .andExpect(status().isOk());
    }

    @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());
    }
}