반응형
50. 50. 인증 - 3 + 51. 51. 인증 - 4
// userservicetest
이메일 비밀번호가 다를때 핸들링을 보고 있다.
package kr.co.fastcampus.eatgo.application;
import kr.co.fastcampus.eatgo.domain.User;
import kr.co.fastcampus.eatgo.domain.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
public class UserServiceTests {
@InjectMocks
private UserService userService;
@Mock
private UserRepository userRepostory;
@Mock
private PasswordEncoder passwordEncoder;
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void authenticateWithValidAttributes() {
String email = "tester@example.com";
String password = "test";
User mockUser = User.builder().email(email).build();
given(userRepostory.findByEmail(email))
.willReturn(Optional.of(mockUser));
given(passwordEncoder.matches(any(), any())).willReturn(true);
User user = userService.authenticate(email, password);
assertThat(user.getEmail()).isEqualTo(email);
}
@Test
public void authenticateWithNotExistedEmail() {
String email = "x@example.com";
String password = "test";
given(userRepostory.findByEmail(email))
.willReturn(Optional.empty());
assertThatThrownBy(() -> {
userService.authenticate(email, password);
}).isInstanceOf(EmailNotExistedException.class);
}
@Test
public void authenticateWithWrongPassword() {
String email = "tester@example.com";
String password = "x";
User mockUser = User.builder().email(email).build();
given(userRepostory.findByEmail(email))
.willReturn(Optional.of(mockUser));
given(passwordEncoder.matches(any(), any())).willReturn(false);
assertThatThrownBy(() -> {
userService.authenticate(email, password);
}).isInstanceOf(PasswordWrongException.class);
}
}
package kr.co.fastcampus.eatgo.interfaces;
import kr.co.fastcampus.eatgo.application.EmailNotExistedException;
import kr.co.fastcampus.eatgo.application.PasswordWrongException;
import kr.co.fastcampus.eatgo.application.UserService;
import kr.co.fastcampus.eatgo.domain.User;
import kr.co.fastcampus.eatgo.utils.JwtUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.core.StringContains.containsString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(SessionController.class)
public class SessionControllerTests {
@Autowired
MockMvc mvc;
@MockBean
private JwtUtil jwtUtil;
@MockBean
private UserService userService;
@Test
public void createWithValidAttributes() throws Exception {
Long id = 1004L;
String email = "tester@example.com";
String name = "Tester";
String password = "test";
User mockUser = User.builder().id(id).name(name).level(1L).build();
given(userService.authenticate(email, password)).willReturn(mockUser);
given(jwtUtil.createToken(id, name, null))
.willReturn("header.payload.signature");
mvc.perform(post("/session")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\":\"tester@example.com\",\"password\":\"test\"}"))
.andExpect(status().isCreated())
.andExpect(header().string("location", "/session"))
.andExpect(content().string(
containsString("{\"accessToken\":\"header.payload.signature\"}")
));
verify(userService).authenticate(eq(email), eq(password));
}
@Test
public void createRestaurantOwner() throws Exception {
Long id = 1004L;
String email = "tester@example.com";
String name = "Tester";
String password = "test";
User mockUser = User.builder()
.id(id)
.name(name)
.level(50L)
.restaurantId(369L)
.build();
given(userService.authenticate(email, password)).willReturn(mockUser);
given(jwtUtil.createToken(id, name, 369L))
.willReturn("header.payload.signature");
mvc.perform(post("/session")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\":\"tester@example.com\",\"password\":\"test\"}"))
.andExpect(status().isCreated())
.andExpect(header().string("location", "/session"))
.andExpect(content().string(
containsString("{\"accessToken\":\"header.payload.signature\"}")
));
verify(userService).authenticate(eq(email), eq(password));
}
@Test
public void createWithNotExistedEmail() throws Exception {
given(userService.authenticate("x@example.com", "test"))
.willThrow(EmailNotExistedException.class);
mvc.perform(post("/session")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\":\"x@example.com\",\"password\":\"test\"}"))
.andExpect(status().isBadRequest());
verify(userService).authenticate(eq("x@example.com"), eq("test"));
}
@Test
public void createWithWrongPassword() throws Exception {
given(userService.authenticate("tester@example.com", "x"))
.willThrow(PasswordWrongException.class);
mvc.perform(post("/session")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\":\"tester@example.com\",\"password\":\"x\"}"))
.andExpect(status().isBadRequest());
verify(userService).authenticate(eq("tester@example.com"), eq("x"));
}
}
nullExceptionErrror 에서는 if( === null) 이라는 조건문을 주면 된다.
substring(0,10);
자바 인강이 듣고 싶다면 =>https://bit.ly/3ilMbIO
반응형
'스프링, 자바' 카테고리의 다른 글
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 41회차 미션 (0) | 2020.09.19 |
---|---|
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 40회차 미션 (0) | 2020.09.18 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 38회차 미션 (0) | 2020.09.16 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 37회차 미션 (0) | 2020.09.15 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 36회차 미션 (0) | 2020.09.14 |