▸ 오늘의 코드카타
▸ Service Test
▸ Controller Test
2024년 2월 22일 - [프로그래머스] 28 : 행렬의 곱셈
@ExtendWith(MockitoExtension.class) //@Mock 사용을 위해 설정
public class TodoServiceTest {
@Mock
TodoRepository todoRepository;
@Mock
CommentService commentService;
@Mock
UserDetailsImpl userDetails;
@Test
@DisplayName("postTodo메서드 - 할일카드 등록 성공")
void test1() {
//given
String title = "제목";
String content = "내용";
TodoRequestDto todoRequestDto = new TodoRequestDto();
todoRequestDto.setTitle(title);
todoRequestDto.setContent(content);
TodoService todoService = new TodoService(todoRepository, commentService);
//when
TodoResponseDto result = todoService.postTodo(todoRequestDto, userDetails);
//then
assertEquals(todoRequestDto.getTitle(), result.getTitle());
assertEquals(todoRequestDto.getContent(), result.getContent());
}
}
@Test
@DisplayName("postTodo 메서드 - 할일카드 등록 실패")
void test2() {
//given
String title = null;
String content = "내용";
TodoRequestDto todoRequestDto = new TodoRequestDto();
todoRequestDto.setTitle(title);
todoRequestDto.setContent(content);
TodoService todoService = new TodoService(todoRepository, commentService);
//when
Exception exception = assertThrows(MethodArgumentNotValidException.class, () -> {
todoService.postTodo(todoRequestDto, userDetails);
});
//then
assertSame("제목을 입력하세요.", exception.getMessage());
}
@Test
@DisplayName("할일카드 조회 성공")
void test2() {
//given
Long id = 1L;
String title = "제목";
String content = "내용";
TodoRequestDto todoRequestDto = new TodoRequestDto();
todoRequestDto.setTitle(title);
todoRequestDto.setContent(content);
Todo todo = new Todo(todoRequestDto, userDetails);
TodoService todoService = new TodoService(todoRepository, commentService);
given(todoRepository.findById(id)).willReturn(Optional.of(todo));
//when
TodoResponseDto result = todoService.getTodoByTodoId(id);
//then
assertEquals(1L,result.getId());
assertEquals("제목", result.getTitle());
assertEquals("내용", result.getContent());
}
@Test
@DisplayName("할일카드 조회 성공")
void test2() {
//given
Long id = 1L;
String title = "제목";
String content = "내용";
TodoRequestDto todoRequestDto = new TodoRequestDto();
todoRequestDto.setTitle(title);
todoRequestDto.setContent(content);
Todo todo = new Todo(todoRequestDto, userDetails);
TodoService todoService = new TodoService(todoRepository, commentService);
given(todoRepository.findById(id)).willReturn(Optional.of(todo));
//when
TodoResponseDto result = todoService.getTodoByTodoId(id);
//then
assertNotNull(result);
}
@Test
@DisplayName("할일카드 조회 실패")
void Test3(){
//given
Long id = 1L;
TodoService todoService = new TodoService(todoRepository, commentService);
//when
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, ()-> {
todoService.getTodoByTodoId(id);
});
//then
assertEquals("존재하지 않는 할일 id 입니다.", exception.getMessage());
}
@Test
@DisplayName("할일카드 수정 성공")
void Test4() {
//given
Long id = 100L;
String title = "제목";
String content = "내용";
String username = "yejin";
TodoRequestDto requestDto = new TodoRequestDto();
requestDto.setTitle(title);
requestDto.setContent(content);
Todo todo = new Todo(requestDto, userDetails);
todo.setUsername(username);
TodoService todoService = new TodoService(todoRepository, commentService);
given(todoRepository.findById(id)).willReturn(Optional.of(todo));
given(userDetails.getUsername()).willReturn(username);
String title1 = "제목1";
String content1 = "내용1";
TodoRequestDto requestDto1 = new TodoRequestDto();
requestDto1.setTitle(title1);
requestDto1.setContent(content1);
//when
TodoResponseDto result = todoService.updateTodo(id, requestDto1, userDetails);
//then
assertEquals(title1, result.getTitle());
assertEquals(content1, result.getContent());
}
@Test
@DisplayName("할일카드 수정 실패")
void Test5() {
//given
Long id = 100L;
String title = "제목";
String content = "내용";
String username = "yejin";
TodoRequestDto requestDto = new TodoRequestDto();
requestDto.setTitle(title);
requestDto.setContent(content);
Todo todo = new Todo(requestDto, userDetails);
todo.setUsername("yejinyejin");
TodoService todoService = new TodoService(todoRepository, commentService);
given(todoRepository.findById(id)).willReturn(Optional.of(todo));
given(userDetails.getUsername()).willReturn(username);
String title1 = "제목1";
String content1 = "내용1";
TodoRequestDto requestDto1 = new TodoRequestDto();
requestDto1.setTitle(title1);
requestDto1.setContent(content1);
//when
Exception exception = assertThrows(RejectedExecutionException.class, ()->{
todoService.updateTodo(id, requestDto1, userDetails);
});
//then
assertEquals("할일카드의 작성자만 수정이 가능합니다.", exception.getMessage());
}
public class MockSpringSecurityFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
SecurityContextHolder.getContext()
.setAuthentication((Authentication) ((HttpServletRequest) req).getUserPrincipal());
chain.doFilter(req, res);
}
@Override
public void destroy() {
SecurityContextHolder.clearContext();
}
}
@WebMvcTest(
controllers = {TodoController.class},
excludeFilters = {
@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
classes = WebSecurityConfig.class
)
}
)
public class UserTodoMvcTest {
private MockMvc mvc;
private Principal mockPrincipal;
@Autowired
private WebApplicationContext context;
@Autowired
private ObjectMapper objectMapper;
@MockBean
TodoService todoService;
@MockBean
UserService userService;
@BeforeEach
public void setup(){
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity(new MockSpringSecurityFilter()))
.build();
}
private void mockUserSetuo(){
String username = "yejin";
String password = "yejin1234";
User testUser = new User(username, password);
UserDetailsImpl userDetails = new UserDetailsImpl(testUser);
mockPrincipal = new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}
@Test
@DisplayName("할일카드 등록 성공")
void test1() throws Exception{
//given
this.mockUserSetuo();
String title = "제목";
String content = "내용";
TodoRequestDto requestDto = new TodoRequestDto();
requestDto.setTitle(title);
requestDto.setContent(content);
String postInfo = objectMapper.writeValueAsString(requestDto);
//when - then
mvc.perform(post("/api/todos")
.content(postInfo)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.principal(mockPrincipal)
)
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/api/todos/myTodos"))
.andDo(print());
}
}
@Test
@DisplayName("할일카드 등록 실패")
void test2() throws Exception{
//given
this.mockUserSetuo();
String title = "";
String content = "내용";
TodoRequestDto requestDto = new TodoRequestDto();
requestDto.setTitle(title);
requestDto.setContent(content);
String postInfo = objectMapper.writeValueAsString(requestDto);
//when - then
mvc.perform(post("/api/todos")
.content(postInfo)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.principal(mockPrincipal)
)
.andExpect(status().isBadRequest())
.andExpect(MockMvcResultMatchers.jsonPath("$.errorMessage").value("제목을 입력하세요."))
.andExpect(MockMvcResultMatchers.jsonPath("$.statusCode").value(400))
.andDo(print());
}