Spring Security in JUnit Test

21-02-2016
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/applicationContext.xml",
        "classpath:/mvc-dispatcher-servlet.xml",
        "classpath:/spring-security.xml"})
@WebAppConfiguration
public class UserControllerTest {

    @Autowired
    private UserService userService;
    @Autowired
    WebApplicationContext wac;
    private MockMvc mockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(springSecurity()).build();
    }

    @Test
    @WithMockUser(username = "myuce")
    public void saveBelge() throws Exception {
        Belge belge = new GumrukServiceUtilTest().createBelge();
        mockMvc.perform(post("/kullanici/belge/kaydet")
                .flashAttr("belge", belge))
                .andExpect(status().isOk());
    }

    @Test
    public void register() throws Exception {
        User user = createUser();
        saveUser(user);
        assertEquals(user.getUsername(), getUserFromDB(user.getUsername()).getUsername());
    }

    private User createUser() {
        User user = new User();
        user.setUsername(RandomStringUtils.random(4, true, false));
        user.setTitle(RandomStringUtils.random(20, true, false));
        user.setName(RandomStringUtils.random(5, true, false));
        user.setSurname(RandomStringUtils.random(5, true, false));
        user.setPassword(RandomStringUtils.random(8, false, true));
        user.setTelephone(RandomStringUtils.random(10, false, true));
        user.setEmail(RandomStringUtils.random(4, true, false) + "@telifhaklari.gov.tr");
        user.setAddress(RandomStringUtils.random(50, true, true));
        return user;
    }

    private void saveUser(User user) throws Exception {
        mockMvc.perform(post("/kayit")
                .param("captcha", "10")
                .with(csrf())
                .sessionAttrs(getCaptcha())
                .flashAttr("user", user))
                .andExpect(status().isOk());
    }


    private Map<String, Object> getCaptcha() {
        Map<String, Object> sessionAttrs = new HashMap<String, Object>();
        sessionAttrs.put("rand1", "5");
        sessionAttrs.put("rand2", "5");
        return sessionAttrs;
    }

    private User getUserFromDB(String username) {
        return userService.getUser(username);
    }

    @Test
    public void saveAdmin() throws Exception {
        User user = createUser();
        UserRole userRole=new UserRole();
        userRole.setUserRoleId(1);
        user.setUserRoleList(Arrays.asList(userRole));
        saveAdmin(user);
        assertEquals(user.getUsername(), getUserFromDB(user.getUsername()).getUsername());
    }

    private void saveAdmin(User user) throws Exception {
        mockMvc.perform(post("/yonetim/home/yonetici/ekle/kaydet")
                .with(csrf())
                .session((MockHttpSession) getHttpSession("SaFv", "14093171"))
                .flashAttr("user", user))
                .andExpect(status().isOk());
    }

    @Test
    public void passwordRemind() throws Exception {
        User user = createUser();
        saveUser(user);
        mockMvc.perform(post("/sifre-hatirlatma")
                .param("username", user.getUsername())
                .param("email", user.getEmail())
                .param("captcha", "10")
                .with(csrf())
                .sessionAttrs(getCaptcha()))
                .andExpect(status().isOk());
    }

    @Test
    public void updateUserInfo() throws Exception {
        User user = createUser();
        saveUser(user);
        String username = user.getUsername();
        String password = user.getPassword();
        User replacedUserInfo = createUser();
        user.setName(replacedUserInfo.getName());
        user.setPassword(replacedUserInfo.getPassword());
        user.setTelephone(replacedUserInfo.getTelephone());
        user.setEmail(replacedUserInfo.getEmail());
        mockMvc.perform(post("/kullanici/bilgilerim/kaydet")
                .flashAttr("user", user)
                .session((MockHttpSession) getHttpSession(username, password))
                .with(csrf()))
                .andExpect(status().isOk());
    }

    @Test
    public void bilgilerim() throws Exception {
        User user = createUser();
        saveUser(user);
        mockMvc.perform(get("/kullanici/bilgilerim")
                .session((MockHttpSession) getHttpSession(user.getUsername(),
                        user.getPassword())))
                .andExpect(status().isOk());
    }

    private HttpSession getHttpSession(String username, String password) throws Exception {
        return mockMvc.perform(post("/login")
                .param("username", username)
                .param("password", password)
                .param("captcha", "10")
                .with(csrf())
                .sessionAttrs(getCaptcha()))
                .andDo(print())
                .andExpect(status().is(HttpStatus.FOUND.value()))
                .andReturn()
                .getRequest()
                .getSession();
    }

    @Test
    public void changePassword() throws Exception {
        User user = createUser();
        saveUser(user);
        String newPassword = createUser().getPassword();
        mockMvc.perform(post("/kullanici/sifre-degistirme")
                .param("oldPassword", user.getPassword())
                .param("newPassword", newPassword)
                .param("retypedNewPassword", newPassword)
                .session((MockHttpSession) getHttpSession(user.getUsername(), user.getPassword()))
                .with(csrf()))
                .andDo(print())
                .andExpect(status().isOk());
    }
}

© 2019 All rights reserved. Codesenior.COM