Skip to content
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
149 changes: 149 additions & 0 deletions docs/misson/day18/README.md
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
58 changes: 58 additions & 0 deletions playground/src/test/java/study/misson18/CommentTest.java
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. 게시물 생성
}
Comment on lines +9 to +15
Copy link
Owner Author

Choose a reason for hiding this comment

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

댓글을 테스트 하기 위해 필요한 사용자 생성 로직과 게시물 생성 로직을 setup 절에 배치


@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의 댓글 수정 시도
}
}