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

3단계 - 테스트를 통한 코드 보호 #532

Open
wants to merge 2 commits into
base: kymiin
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions src/test/java/kitchenpos/ApplicationTest.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package kitchenpos;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;

@SpringBootTest
class ApplicationTest {
@Test
void contextLoads() {
}
}
@ExtendWith(MockitoExtension.class)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mockito를 이용하여 테스트 코드를 작성해 주셨네요 :)
혹시 통합 테스트 또는 가짜 객체를 사용해서 테스트 코드를 작성할 수도 있었을텐데 그렇게 하지 않은 이유는 어떤 걸까요?

  • 이렇게 질문 드린 이유는 이런 고민 과정을 통해 특정 상황에서 자신만의 기준을 확립해 나가시면 좋을 듯 해서예요!

public class ApplicationTest {

}
90 changes: 90 additions & 0 deletions src/test/java/kitchenpos/application/MenuGroupServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package kitchenpos.application;

import kitchenpos.ApplicationTest;
import kitchenpos.domain.MenuGroup;
import kitchenpos.domain.MenuGroupRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import static kitchenpos.fixture.MenuGroupFixtures.메뉴_그룹_등록;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;

@DisplayName("메뉴그룹")
public class MenuGroupServiceTest extends ApplicationTest {
@Mock
private MenuGroupRepository menuGroupRepository;

@InjectMocks
private MenuGroupService menuGroupService;

@BeforeEach
void setUp() {
menuGroupService = new MenuGroupService(menuGroupRepository);
}

@DisplayName("메뉴 그룹 전체 조회한다.")
@Test
public void findAll() {
// given
MenuGroup 등심_메뉴_그룹 = 메뉴_그룹_등록("등심세트");
MenuGroup 안심_메뉴_그룹 = 메뉴_그룹_등록("안심세트");
given(menuGroupRepository.findAll()).willReturn(Arrays.asList(등심_메뉴_그룹, 안심_메뉴_그룹));

// when
List<MenuGroup> menuGroups = menuGroupService.findAll();

// then
assertAll(
() -> assertThat(menuGroups.size()).isEqualTo(2),
() -> assertThat(menuGroups).containsExactly(등심_메뉴_그룹, 안심_메뉴_그룹)
);
}

@DisplayName("메뉴 그룹을 등록한다.")
@ParameterizedTest
@ValueSource(strings = {"등심세트"})
public void create(String name) {
// given
MenuGroup menuGroup = 메뉴_그룹_등록(name);
given(menuGroupRepository.save(any())).willReturn(menuGroup);


// when
MenuGroup createdMenuGroup = menuGroupService.create(menuGroup);

// then
assertAll(
() -> assertThat(createdMenuGroup.getId()).isInstanceOf(UUID.class),
() -> assertThat(createdMenuGroup.getName()).isEqualTo(name)
);

}

@DisplayName("메뉴 그룹 등록시 이름을 체크 한다.")
@ParameterizedTest
@NullAndEmptySource
public void createWithName(String name) {
// given
MenuGroup emptyMenu = 메뉴_그룹_등록(name);

// when, then
assertThatThrownBy(() -> menuGroupService.create(emptyMenu))
.isInstanceOf(IllegalArgumentException.class);
}


}
160 changes: 160 additions & 0 deletions src/test/java/kitchenpos/application/MenuServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package kitchenpos.application;

import kitchenpos.ApplicationTest;
import kitchenpos.domain.*;
import kitchenpos.infra.PurgomalumClient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import java.math.BigDecimal;
import java.util.*;

import static kitchenpos.fixture.MenuFixtures.메뉴_상품_등록;
import static kitchenpos.fixture.MenuFixtures.메뉴_상품_등록_요청;
import static kitchenpos.fixture.ProductFixtures.상품_등록;
import static kitchenpos.fixture.MenuFixtures.메뉴_등록;
import static kitchenpos.fixture.MenuFixtures.메뉴_등록_요청;
import static kitchenpos.fixture.MenuGroupFixtures.메뉴_그룹_등록;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.when;

@DisplayName("메뉴")
public class MenuServiceTest extends ApplicationTest {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

메뉴 가격 변경메뉴 노출 로직에 대해서도 테스트 코드를 작성해보시면 좋을 것 같아요 :)
기존 레거시 코드에 버그가 숨어 있을 수도 있잖아요~

@Mock
private MenuRepository menuRepository;
@Mock
private MenuGroupRepository menuGroupRepository;
@Mock
private ProductRepository productRepository;
@Mock
PurgomalumClient purgomalumClient;

@InjectMocks
private MenuService menuService;

private UUID id;
private Product 등심돈까스_상품;
private MenuGroup 등심돈까스_메뉴_그룹;
private Menu 등심돈까스_메뉴_등록;
private Menu 등심_세트_메뉴;
private MenuProduct 등심_세트_메뉴_상품;


@BeforeEach
void setUp() {
menuService = new MenuService(menuRepository, menuGroupRepository, productRepository, purgomalumClient);

id = UUID.randomUUID();
등심돈까스_상품 = 상품_등록("등심돈까스", 15000);
등심돈까스_메뉴_그룹 = 메뉴_그룹_등록("등심세트");

등심돈까스_메뉴_등록 = 메뉴_등록_요청("등심돈까스", 15000, true, List.of(메뉴_상품_등록_요청(1L)));
등심_세트_메뉴 = 메뉴_등록("등심돈까스", 15000, true,
List.of(메뉴_상품_등록(등심돈까스_상품, 1L)));
등심_세트_메뉴_상품 = 메뉴_상품_등록(상품_등록("등심돈까스", 15000), 1L);


}


@DisplayName("메뉴 전체를 조회한다.")
@Test
public void findAll() {
// given
Menu 등심돈까스 = 메뉴_등록();
Menu 안심돈까스_세트 = 메뉴_등록("안심돈까스_세트", 20000,
List.of(메뉴_상품_등록(상품_등록("안심돈까스", 18000), 1L),
메뉴_상품_등록(상품_등록("음료", 3000), 1L)));
given(menuRepository.findAll()).willReturn(Arrays.asList(등심돈까스, 안심돈까스_세트));

// when
List<Menu> menus = menuService.findAll();

// then
assertAll(
() -> assertThat(menus.size()).isEqualTo(2)
);
}


@DisplayName("메뉴를 등록한다.")
@Test
public void create() {
// given
given(menuGroupRepository.findById(any())).willReturn(Optional.of(등심돈까스_메뉴_그룹));
given(productRepository.findAllByIdIn(any())).willReturn(Arrays.asList(등심돈까스_상품));
given(productRepository.findById(any())).willReturn(Optional.of(등심돈까스_상품));
given(purgomalumClient.containsProfanity(anyString())).willReturn(false);
given(menuRepository.save(any())).willReturn(등심_세트_메뉴);


// when
Menu createdMenu = menuService.create(등심돈까스_메뉴_등록);

// then
assertAll(
() -> assertThat(createdMenu.getName()).isEqualTo("등심돈까스"),
() -> assertThat(createdMenu.getPrice()).isEqualTo(BigDecimal.valueOf(15000)),
() -> assertThat(createdMenu.isDisplayed()).isEqualTo(true),
() -> assertThat(createdMenu.getMenuProducts().size()).isEqualTo(1),
() -> assertThat(createdMenu.getMenuProducts().get(0).getQuantity()).isEqualTo(1L),
() -> assertThat(createdMenu.getMenuProducts().get(0).getProduct().getPrice()).isEqualTo(BigDecimal.valueOf(15000)),
() -> assertThat(createdMenu.getMenuProducts().get(0).getProduct().getName()).isEqualTo("등심돈까스")
);
}


@DisplayName("메뉴 등록시 상품 가격(음수)을 체크 한다.")
@ParameterizedTest
@ValueSource(ints = {-10000})
public void createCheckPrice(int price) {
// given
Menu menu = 메뉴_등록("등심돈까스", price, null);

// when, then
assertThatThrownBy(() -> menuService.create(menu))
.isInstanceOf(IllegalArgumentException.class);
}


@DisplayName("메뉴 등록시 메뉴그룹 포함 여부 체크 한다.")
@Test
public void createCheckMenuGroup() {
// given
given(menuGroupRepository.findById(any())).willReturn(Optional.empty());

// when, then
assertThatThrownBy(() -> menuService.create(등심돈까스_메뉴_등록))
.isInstanceOf(NoSuchElementException.class);
}


@DisplayName("메뉴 등록시 메뉴 이름(비속어)을 체크 한다.")
@ParameterizedTest
@ValueSource(strings = {"fuck"})
public void createWithoutBadWord(String name) {
// given
Menu menu = 메뉴_등록_요청(name, 15000, true, Arrays.asList(등심_세트_메뉴_상품));

given(productRepository.findAllByIdIn(any())).willReturn(Arrays.asList(등심돈까스_상품));
given(productRepository.findById(any())).willReturn(Optional.of(등심돈까스_상품));
given(menuGroupRepository.findById(any())).willReturn(Optional.of(등심돈까스_메뉴_그룹));
given(purgomalumClient.containsProfanity(anyString())).willReturn(true);

// when, then
assertThatThrownBy(() -> menuService.create(menu))
.isInstanceOf(IllegalArgumentException.class);
}


}
Loading