Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[refactor/Inhabas#165] 테스트 코드 리펙토링 #221

Closed
wants to merge 9 commits into from
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,23 @@ public void Contents_is_too_long() {

//then
assertThatThrownBy(() -> new Content(contentsString))
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
}

@DisplayName("Content 타입에 공백을 저장할 수 없다.")
@Test
public void Contents_is_Empty() {
assertThatThrownBy(() -> new Content(""))
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
}

@DisplayName("Content 타입에 null 은 허용 안된다.")
@Test
public void Contents_is_Null() {
assertThatThrownBy(() -> new Content(null))
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.inhabas.api.auth.domain.error.businessException.InvalidInputException;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

Expand All @@ -30,23 +31,23 @@ public void Title_is_too_long() {

//then
assertThatThrownBy(() -> new Title(titleString))
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
}

@DisplayName("제목은 null 일 수 없습니다.")
@Test
public void Title_cannot_be_Null() {
assertThatThrownBy(() -> new Title(null))
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
}

@DisplayName("제목은 빈 문자열일 수 없습니다.")
@Test
public void Title_cannot_be_Blank() {
assertThatThrownBy(() -> new Title(""))
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
.isInstanceOf(InvalidInputException.class)
.hasMessage("입력값이 없거나, 타입이 유효하지 않습니다.");
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package com.inhabas.api.domain.board.dto;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.inhabas.api.domain.board.dto.SaveBoardDto;
import com.inhabas.api.domain.menu.domain.valueObject.MenuId;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.inhabas.api.domain.menu.domain.valueObject.MenuId;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
Expand Down Expand Up @@ -40,7 +42,7 @@ public void SaveBoardDto_is_OK(){
Set<ConstraintViolation<SaveBoardDto>> violations = validator.validate(saveBoardDto);

// then
assertTrue(violations.isEmpty());
assertThat(violations).isEmpty();
}

@DisplayName("SaveBoardDto의 content 필드가 null 이면 validation 실패")
Expand All @@ -53,8 +55,10 @@ public void Contents_is_null() {
Set<ConstraintViolation<SaveBoardDto>> violations = validator.validate(saveBoardDto);

// then
assertEquals(1, violations.size());
assertEquals("본문을 입력하세요.", violations.iterator().next().getMessage());
assertThat(violations).hasSize(1);
assertThat(violations.iterator().next().getMessage())
.as("violations 컬렉션의 첫 번째 요소의 메시지가 \"본문을 입력하세요.\"와 동일해야 합니다.")
.isEqualTo("본문을 입력하세요.");
}

@DisplayName("게시글의 제목이 100자 이상을 넘긴 경우 validation 통과하지 못함.")
Expand All @@ -70,8 +74,10 @@ public void Title_is_too_long() {
Set<ConstraintViolation<SaveBoardDto>> violations = validator.validate(saveBoardDto);

// then
assertEquals(1, violations.size());
assertEquals("제목은 최대 100자입니다.", violations.iterator().next().getMessage());
assertThat(violations).hasSize(1);
assertThat(violations.iterator().next().getMessage())
.as("violations 컬렉션의 첫 번째 요소의 메시지가 \"제목은 최대 100자입니다.\"와 동일해야 합니다.")
.isEqualTo("제목은 최대 100자입니다.");
}

}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.inhabas.api.domain.board.dto;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
Expand Down Expand Up @@ -38,7 +40,7 @@ public void UpdateBoardDto_is_OK() {
Set<ConstraintViolation<UpdateBoardDto>> violations = validator.validate(updateBoardDto);

// then
assertEquals(0, violations.size());
assertThat(violations).hasSize(0);
}

@DisplayName("본문에 공백이 입력되었을 경우 테스트를 통과하지 못함.")
Expand All @@ -51,7 +53,9 @@ public void Contents_is_empty() {
Set<ConstraintViolation<UpdateBoardDto>> violations = validator.validate(updateBoardDto);

// then
assertEquals(1, violations.size());
assertEquals("본문을 입력하세요", violations.iterator().next().getMessage());
assertThat(violations).hasSize(1);
assertThat(violations.iterator().next().getMessage())
.as("violations 컬렉션의 첫 번째 요소의 메시지가 \"본문을 입력하세요.\"와 동일해야 합니다.")
.isEqualTo("본문을 입력하세요.");
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
package com.inhabas.api.domain.board.usecase;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.inhabas.api.auth.domain.oauth2.member.domain.valueObject.StudentId;
import com.inhabas.api.domain.board.BoardCannotModifiableException;
import com.inhabas.api.domain.board.domain.NormalBoard;
Expand All @@ -8,39 +23,22 @@
import com.inhabas.api.domain.board.dto.UpdateBoardDto;
import com.inhabas.api.domain.board.repository.NormalBoardRepository;
import com.inhabas.api.domain.menu.domain.valueObject.MenuId;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.assertj.core.api.Assertions;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(MockitoExtension.class)
public class BoardServiceTest {

@InjectMocks
BoardServiceImpl boardService;
@InjectMocks BoardServiceImpl boardService;

@Mock
NormalBoardRepository boardRepository;
@Mock NormalBoardRepository boardRepository;

private MockMvc mockMvc;

Expand All @@ -52,7 +50,7 @@ void setUp() {
@DisplayName("게시판을 성공적으로 생성한다.")
@Test
public void createBoard() {
//given
// given
SaveBoardDto saveBoardDto = new SaveBoardDto("title", "content", new MenuId(1));
NormalBoard normalBoard = new NormalBoard("title", "content");
given(boardRepository.save(any())).willReturn(normalBoard);
Expand All @@ -67,15 +65,27 @@ public void createBoard() {
@DisplayName("게시판의 목록을 조회한다.")
@Test
public void getBoardList() {
//given
// given
PageRequest pageable = PageRequest.of(0, 10, Sort.Direction.ASC, "created");

BoardDto boardDto1 =
new BoardDto(1, "title", "content", "mingyeom",
new MenuId(1), LocalDateTime.now(), LocalDateTime.now());
new BoardDto(
1,
"title",
"content",
"mingyeom",
new MenuId(1),
LocalDateTime.now(),
LocalDateTime.now());
BoardDto boardDto2 =
new BoardDto(2, "title", "content", "minji",
new MenuId(1), LocalDateTime.now(), LocalDateTime.now());
new BoardDto(
2,
"title",
"content",
"minji",
new MenuId(1),
LocalDateTime.now(),
LocalDateTime.now());

List<BoardDto> results = new ArrayList<>();
results.add(boardDto1);
Expand All @@ -84,21 +94,20 @@ public void getBoardList() {

given(boardRepository.findAllByMenuId(any(), any())).willReturn(expectedBoardDto);

//when
// when
Page<BoardDto> returnedBoardList = boardService.getBoardList(new MenuId(1), pageable);

//then
// then
then(boardRepository).should(times(1)).findAllByMenuId(any(), any());
assertThat(returnedBoardList).isEqualTo(expectedBoardDto);
Assertions.assertThat(returnedBoardList).isEqualTo(expectedBoardDto);
}

@DisplayName("게시글 단일 조회에 성공한다.")
@Test
public void getDetailBoard() {
//given
// given
BoardDto boardDto =
new BoardDto(1, "title", "content", "김민겸",
new MenuId(1), LocalDateTime.now(), null);
new BoardDto(1, "title", "content", "김민겸", new MenuId(1), LocalDateTime.now(), null);
given(boardRepository.findDtoById(any())).willReturn(Optional.of(boardDto));

// when
Expand All @@ -111,7 +120,7 @@ public void getDetailBoard() {
@DisplayName("게시글을 성공적으로 삭제한다.")
@Test
public void deleteBoard() {
//given
// given
StudentId writer = new StudentId("12201863");
NormalBoard board = new NormalBoard("Title", "Content").writtenBy(writer);
given(boardRepository.findById(anyInt())).willReturn(Optional.of(board));
Expand All @@ -127,12 +136,11 @@ public void deleteBoard() {
@DisplayName("게시글을 수정한다.")
@Test
public void updateBoard() {
//given
// given
StudentId memberId = new StudentId("12201863");
NormalBoard savedNormalBoard = new NormalBoard("Origin Title",
"Origin Content").writtenBy(memberId);
NormalBoard updatedNormalBoard = new NormalBoard("Title", "Content").writtenBy(
memberId);
NormalBoard savedNormalBoard =
new NormalBoard("Origin Title", "Origin Content").writtenBy(memberId);
NormalBoard updatedNormalBoard = new NormalBoard("Title", "Content").writtenBy(memberId);

given(boardRepository.findById(anyInt())).willReturn(Optional.of(savedNormalBoard));
given(boardRepository.save(any())).willReturn(updatedNormalBoard);
Expand All @@ -149,28 +157,31 @@ public void updateBoard() {
@DisplayName("작성자가 아니면 게시글 수정에 실패한다.")
@Test
public void failToUpdateBoard() {
//given
// given
StudentId badUser = new StudentId("44444444");
StudentId originWriter = new StudentId("12201863");
NormalBoard board = new NormalBoard("Title", "Content").writtenBy(originWriter);
given(boardRepository.findById(anyInt())).willReturn(Optional.of(board));

// when
Assertions.assertThrows(BoardCannotModifiableException.class,
() -> boardService.update(badUser, new UpdateBoardDto(1, "수정된 제목", "수정된 내용")));
Assertions.assertThatThrownBy(
() -> boardService.update(badUser, new UpdateBoardDto(1, "수정된 제목", "수정된 내용")))
.isInstanceOf(BoardCannotModifiableException.class)
.hasMessage("다른 작성자가 작성한 글은 수정할 수 없습니다!");
}

@DisplayName("작성자가 아니면 게시글 삭제에 실패한다.")
@Test
public void failToDeleteBoard() {
//given
// given
StudentId badUser = new StudentId("44444444");
StudentId originWriter = new StudentId("12201863");
NormalBoard board = new NormalBoard("Title", "Content").writtenBy(originWriter);
given(boardRepository.findById(anyInt())).willReturn(Optional.of(board));

// when
Assertions.assertThrows(BoardCannotModifiableException.class,
() -> boardService.delete(badUser, 1));
Assertions.assertThatThrownBy(() -> boardService.delete(badUser, 1))
.isInstanceOf(BoardCannotModifiableException.class)
.hasMessage("다른 작성자가 작성한 글은 수정할 수 없습니다!");
}
}
Loading
Loading