Skip to content
This repository has been archived by the owner on Aug 13, 2022. It is now read-only.

Commit

Permalink
#2 userService 테스트코드 추가(83% methods, 95% lines covered)
Browse files Browse the repository at this point in the history
  • Loading branch information
jsy3831 committed Sep 27, 2021
1 parent d4b7e9d commit f935896
Show file tree
Hide file tree
Showing 6 changed files with 135 additions and 32 deletions.
4 changes: 2 additions & 2 deletions src/main/java/com/photobook/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,9 @@ public Response checkUserId(@PathVariable @NotBlank String id) {

@DeleteMapping("/my-info")
@LoginCheck
public Response deleteUser(@LoginUser UserDto loginUser) {
public Response deleteUser(@RequestParam @NotBlank String password, @LoginUser UserDto loginUser) {

userService.deleteUser(loginUser.getId());
userService.deleteUser(loginUser, password);

loginService.removeLoginUserInfo();

Expand Down
14 changes: 0 additions & 14 deletions src/main/java/com/photobook/exception/ExceptionType.java

This file was deleted.

2 changes: 1 addition & 1 deletion src/main/java/com/photobook/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ public interface UserService {

void validateUserId(String id);

void deleteUser(String id);
void deleteUser(UserDto userInfo, String password);
}
14 changes: 12 additions & 2 deletions src/main/java/com/photobook/service/impl/UserServiceImpl.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.photobook.service.impl;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
Expand Down Expand Up @@ -64,7 +66,15 @@ public void validateUserId(String id) {
}

@Override
public void deleteUser(String id) {
userMapper.deleteUser(id);
@CacheEvict(value = "findUserCache", key = "#userInfo.getId()")
public void deleteUser(UserDto userInfo, String password) {

boolean isPwdMatch = passwordEncoder.matches(password, userInfo.getPassword());

if (!isPwdMatch) {
throw new BadCredentialsException("일치하지않는 비밀번호입니다.");
}

userMapper.deleteUser(userInfo.getId());
}
}
16 changes: 16 additions & 0 deletions src/main/resources/ehcache.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,24 @@
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">

<!-- 임시저장경로 지정 -->
<diskStore path="java.io.tmpdir" />

<!--
maxEntriesLocalHeap - 메모리에 생성될 객체의 최대 수(0: 제한없음)
maxEntriesLocalDisk - 디스크(DiskStore)에 저장될 객체의 최대 수(0: 제한없음)
eternal - 저장된 캐시를 제거할지 여부. 설정이 true 인 경우 저장된 캐시는 제거되지 않으며
timeToIdleSeconds, timeToLiveSeconds 설정은 무시
timeToIdleSeconds - 생성후 해당 시간 동안 캐시가 사용되지 않으면 삭제, 0은 삭제되지 않음
timeToLiveSeconds - 생성후 해당 시간이 지나면 캐시는 삭제. 0은 삭제되지 않음
diskSpoolBufferSizeMB - 디스크 캐시에 쓰기 모드로 들어갈때, 사용될 비동기 모드의 스폴 버퍼 크기 설정
memoryStoreEvictionPolicy - maxEntriesLocalHeap 설정 값에 도달했을때 설정된 정책에 따라 객체가 제거되고 새로 추가
LRU : 사용이 가장 적었던 것부터 제거
FIFO : 먼저 입력된 것부터 제거
LFU : 사용량이 적은 것부터 제거
persistence strategy - diskStore 사용 설정("localTempSwap": Temp DiskStore 사용, "none": Only Memory 사용)
-->
<cache name="findUserCache"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="1000"
Expand Down
117 changes: 104 additions & 13 deletions src/test/java/com/photobook/service/impl/UserServiceImplTest.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package com.photobook.service.impl;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

import java.time.LocalDate;

Expand All @@ -17,6 +16,7 @@
import org.springframework.security.crypto.password.PasswordEncoder;

import com.photobook.dto.UserDto;
import com.photobook.exception.customexception.DuplicatedException;
import com.photobook.mapper.UserMapper;

@ExtendWith(MockitoExtension.class)
Expand All @@ -35,7 +35,8 @@ public UserDto userInfo() {
UserDto userInfo = new UserDto();
userInfo.setUserId(1);
userInfo.setId("admin");
userInfo.setPassword(passwordEncoder.encode("1234"));
// userInfo.setPassword(passwordEncoder.encode("1234"));
userInfo.setPassword("1234");
userInfo.setName("관리자");
userInfo.setEmail("admin@gmail.com");
userInfo.setBirth(LocalDate.of(1993, 10, 28));
Expand All @@ -49,27 +50,27 @@ public UserDto userInfo() {
@Test
@DisplayName("로그인 검증 성공")
public void successValidateLogin() {
//given
// given
UserDto userInfo = userInfo();
when(userMapper.getUserInfoById("admin")).thenReturn(userInfo);
when(passwordEncoder.matches("1234", userInfo.getPassword())).thenReturn(true);

//when
// when
UserDto result = userServiceImpl.validateLogin("admin", "1234");

//then
// then
assertEquals(result, userInfo);
}

@Test
@DisplayName("로그인 검증 실패_존재하지 않는 아이디")
public void failureValidateLoginId() {
//given
// given
when(userMapper.getUserInfoById("admin")).thenReturn(null);

//then
// then
assertThrows(InternalAuthenticationServiceException.class, () -> {
//when
// when
userServiceImpl.validateLogin("admin", "1234");
});

Expand All @@ -78,16 +79,106 @@ public void failureValidateLoginId() {
@Test
@DisplayName("로그인 검증 실패_비밀번호 불일치")
public void failureValidateLoginPwd() {
//given
// given
UserDto userInfo = userInfo();
when(userMapper.getUserInfoById("admin")).thenReturn(userInfo);
when(passwordEncoder.matches("1234", userInfo.getPassword())).thenReturn(false);

//then
// then
assertThrows(BadCredentialsException.class, () -> {
//when
// when
userServiceImpl.validateLogin("admin", "1234");
});
}

@Test
@DisplayName("아이디 검증 성공_사용가능한 아이디")
public void successValidateUserId() {
// given
when(userMapper.checkUserId("admin")).thenReturn(false);

// when
userServiceImpl.validateUserId("admin");

// then
verify(userMapper, times(1)).checkUserId("admin");
}

@Test
@DisplayName("아이디 검증 실패_중복된 아이디")
public void failureValidateUserId() {
// given
when(userMapper.checkUserId("admin")).thenReturn(true);

// then
assertThrows(DuplicatedException.class, () -> {
// when
userServiceImpl.validateUserId("admin");
});
}

@Test
@DisplayName("회원가입 성공")
public void successCreateUser() {
// given
UserDto userInfo = userInfo();
when(userMapper.checkUserId(userInfo.getId())).thenReturn(false);
doNothing().when(userMapper).createUser(userInfo);

// when
userServiceImpl.createUser(userInfo);

// then
verify(userMapper, times(1)).createUser(userInfo);
}

@Test
@DisplayName("회원가입 실패_중복된 아이디")
public void failureCreateUser() {
// given
UserDto userInfo = userInfo();
when(userMapper.checkUserId(userInfo.getId())).thenReturn(true);

// then
assertThrows(DuplicatedException.class, () -> {
// when
userServiceImpl.createUser(userInfo);
});

// then
verify(userMapper, times(0)).createUser(userInfo);
}

@Test
@DisplayName("회원탈퇴 성공")
public void successDeleteUser() {
// given
UserDto userInfo = userInfo();
when(passwordEncoder.matches("1234", userInfo.getPassword())).thenReturn(true);
doNothing().when(userMapper).deleteUser(userInfo.getId());

// when
userServiceImpl.deleteUser(userInfo, "1234");

// then
verify(userMapper, times(1)).deleteUser(userInfo.getId());
}

@Test
@DisplayName("회원탈퇴 실패_비밀번호 불일치")
public void failureDeleteUser() {
// given
UserDto userInfo = userInfo();
when(passwordEncoder.matches("1234", userInfo.getPassword())).thenReturn(false);

// then
assertThrows(BadCredentialsException.class, () -> {
// when
userServiceImpl.deleteUser(userInfo, "1234");
});

// then
verify(userMapper, times(0)).deleteUser(userInfo.getId());
}

}

0 comments on commit f935896

Please sign in to comment.