-
Notifications
You must be signed in to change notification settings - Fork 0
[미션 Day 18] Mock 어노테이션 종류 및 차이점 & BDD 패턴 매치 #9
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
Open
discphy
wants to merge
5
commits into
misson/day16
Choose a base branch
from
misson/day18
base: misson/day16
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b1fcc4b
:test_tube: 미션 Day 18 @BeforeEach 및 BDD 패턴 배치
discphy d96614f
:test_tube: 미션 Day 18 README 추가
discphy 33ec8e8
:memo: 미션 Day 18 작성
discphy 9b6640b
Merge branch 'misson/day16' into misson/day18
discphy 1dc9cf9
:memo: 미션 Day 18 출처 추가
discphy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| # 미션 - Day18 | ||
|
|
||
| ## @Mock, @MockBean, @Spy, @SpyBean, @InjectMocks의 차이 | ||
|
|
||
| ### @Mock vs @MockBean | ||
|
|
||
| **@Mock** | ||
|
|
||
| + 순수한 Mockito 객체에 사용한다. | ||
| + @InjectMocks나 수동으로 주입 받는다. | ||
| + Spring Context와 무관하다. | ||
|
|
||
| ```java | ||
| @ExtendWith(MockitoExtension.class) // ✅ Spring Context 없이 Mockito 사용 | ||
| class ProductServiceTest { | ||
|
|
||
| @Mock | ||
| private ProductRepository productRepository; // ✅ 직접 Mock 객체 생성 | ||
|
|
||
| @InjectMocks | ||
| private ProductService productService; // ✅ @Mock 어노테이션이 있는 객체 자동 주입 | ||
|
|
||
| @Test | ||
| void testFindAllProducts() { | ||
| // given | ||
| when(productRepository.findAll()).thenReturn(List.of(new Product("001", "Coffee"))); | ||
|
|
||
| // when | ||
| List<Product> products = productService.getAllProducts(); | ||
|
|
||
| // then | ||
| assertThat(products).hasSize(1); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| **@MockBean** | ||
|
|
||
| + 스프링 빈을 Mocking할 때 사용 | ||
| + @Autowired를 통해 자동 주입 받는다. | ||
| + Spring Context에서 관리한다. | ||
|
|
||
| 💡 MockBean이 있을 경우 서버가 새로 뜨기 때문에 따로 관리하는 것을 권장한다. | ||
|
|
||
| ```java | ||
| @SpringBootTest | ||
| class ProductServiceTest { | ||
|
|
||
| @MockBean | ||
| private ProductRepository productRepository; // ✅ Repository를 Mocking -> 따로 빼서 Support 클래스로 관리하는 것을 권장 | ||
|
|
||
| @Autowired | ||
| private ProductService productService; | ||
|
|
||
| @Test | ||
| void testFindAllProducts() { | ||
| // given | ||
| when(productRepository.findAll()).thenReturn(List.of(new Product("001", "Coffee"))); | ||
|
|
||
| // when | ||
| List<Product> products = productService.getAllProducts(); | ||
|
|
||
| // then | ||
| assertThat(products).hasSize(1); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| ### @Spy vs @SpyBean | ||
|
|
||
| **@Spy** | ||
|
|
||
| + @Mock은 객체 전체를 Mocking 했다면, @Spy는 객체의 일부 동작만 Mocking 한다. | ||
| + @Mock과 마찬가지로 순수 Mockito 객체를 사용하며, Spring Context와 무관하다. | ||
|
|
||
| 💡 실제 객체를 활용하기 때문에 @Spy는 when을 쓰면 안된다. doReturn을 사용하여 특정 메서드만 stubbing 된다. | ||
|
|
||
| ```java | ||
| @ExtendWith(MockitoExtension.class) | ||
| class ProductServiceTest { | ||
|
|
||
| @Spy | ||
| private ProductRepository productRepository = new ProductRepository(); // ✅ Spy 객체 생성 | ||
|
|
||
| @InjectMocks | ||
| private ProductService productService; | ||
|
|
||
| @Test | ||
| void testFindAllProducts() { | ||
| // given | ||
| doReturn(List.of(new Product("001", "Coffee"))).when(productRepository).findAll(); // ✅ productRepository.findAll()만 Mocking한다. | ||
|
|
||
| // when | ||
| List<Product> products = productService.getAllProducts(); | ||
|
|
||
| // then | ||
| assertThat(products).hasSize(1); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| **@SpyBean** | ||
|
|
||
| + @Mock과 @MockBean의 관계처럼 @SpyBean도 @Spy를 Spring Context에서 관리하는 어노테이션이다. | ||
|
|
||
| ```java | ||
| @SpringBootTest | ||
| class ProductServiceTest { | ||
|
|
||
| @SpyBean | ||
| private ProductRepository productRepository = new ProductRepository(); // ✅ Repository를 SpyBean으로 변경 | ||
|
|
||
| @Autowired | ||
| private ProductService productService; | ||
|
|
||
| @Test | ||
| void testFindAllProducts() { | ||
| // given | ||
| doReturn(List.of(new Product("001", "Coffee"))).when(productRepository).findAll(); // ✅ productRepository.findAll()만 Mocking한다. | ||
|
|
||
| // when | ||
| List<Product> products = productService.getAllProducts(); | ||
|
|
||
| // then | ||
| assertThat(products).hasSize(1); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| ### @InjectMocks | ||
|
|
||
| + 순수한 Mockito 객체(@Mock, @Spy)를 자동으로 주입할 때 사용 | ||
| + Spring Context에서는 @Autowired를 통해 @MockBean, @SpyBean 객체를 자동 주입 해줬다면, 순수한 Mock을 사용할 때는 @InjectMocks으로 주입을 해주어야 한다. | ||
|
|
||
| ### 순수한 Mock vs 스프링 컨텍스트 | ||
|
|
||
| **Mock 사용 대상** | ||
|
|
||
| | | 순수한 Mock | 스프링 컨텍스트 | | ||
| |--------------|----------|----------| | ||
| | @Mock | ✅ | ❌ | | ||
| | @MockBean | ❌ | ✅ | | ||
| | @Spy | ✅ | ❌ | | ||
| | @SpyBean | ❌ | ✅ | | ||
| | @InjectMocks | ✅ | ❌ | | ||
|
|
||
| [출처] | ||
| + 인프런 워밍업 클럽 : https://www.inflearn.com/course/offline/warmup-club-3-be-code | ||
| + 강의 : https://www.inflearn.com/course/readable-code-%EC%9D%BD%EA%B8%B0%EC%A2%8B%EC%9D%80%EC%BD%94%EB%93%9C-%EC%9E%91%EC%84%B1%EC%82%AC%EA%B3%A0%EB%B2%95/dashboard |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| package study.misson18; | ||
|
|
||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| class CommentTest { | ||
|
|
||
| @BeforeEach | ||
| void setUp() { | ||
| 1-1. 2-1. 3-1. 사용자 생성에 필요한 내용 준비 | ||
| 1-2. 2-2. 3-2. 사용자 생성 | ||
| 1-3. 2-3. 3-5. 게시물 생성에 필요한 내용 준비 | ||
| 1-4. 2-4. 3-6. 게시물 생성 | ||
| } | ||
|
|
||
| @DisplayName("사용자가 댓글을 작성할 수 있다.") | ||
| @Test | ||
| void writeComment() { | ||
| // given | ||
| 1-5. 댓글 생성에 필요한 내용 준비 | ||
|
|
||
| // when | ||
| 1-6. 댓글 생성 | ||
|
|
||
| // then | ||
| 검증 | ||
| } | ||
|
|
||
| @DisplayName("사용자가 댓글을 수정할 수 있다.") | ||
| @Test | ||
| void updateComment() { | ||
| // given | ||
| 2-5. 댓글 생성에 필요한 내용 준비 | ||
| 2-6. 댓글 생성 | ||
|
|
||
| // when | ||
| 2-7. 댓글 수정 | ||
|
|
||
| // then | ||
| 검증 | ||
| } | ||
|
|
||
| @DisplayName("자신이 작성한 댓글이 아니면 수정할 수 없다.") | ||
| @Test | ||
| void cannotUpdateCommentWhenUserIsNotWriter() { | ||
| // given | ||
| 3-3. 사용자2 생성에 필요한 내용 준비 | ||
| 3-4. 사용자2 생성 | ||
|
|
||
| 3-7. 사용자1의 댓글 생성에 필요한 내용 준비 | ||
| 3-8. 사용자1의 댓글 생성 | ||
|
|
||
| // when & then | ||
| 예외 검증 | ||
| 3-9. 사용자2가 사용자1의 댓글 수정 시도 | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
댓글을 테스트 하기 위해 필요한 사용자 생성 로직과 게시물 생성 로직을
setup절에 배치