JUnit์ผ๋ก ์ํ ์ญ์ ๊ธฐ๋ฅ ํ ์คํธ ์ฝ๋ ์์ฑํ๊ธฐ
์ํ ์ญ์ ๊ธฐ๋ฅ์ ํ ์คํธํ๋ ์ฝ๋๋ฅผ ์์ฑํ๋ฉด์ ์ค๋ช ํด๋ณด๊ฒ ์ต๋๋ค.
@Mock
private ProductRepository productRepository;
@InjectMocks
private ProductService productServiceUnderTest;
ํ ์คํธ๋ฅผ ์งํํ ํด๋์ค ์์ @Mock ์ด๋ ธํ ์ด์ ์ ํตํด์ ํ ์คํธ๋ฅผ ์งํํ ๊ฐ์ง ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด์ค๋๋ค.
๋ค์์ผ๋ก ํ ์คํธ๋ฅผ ์งํํ ๋ฉ์๋ ์์ @Test ์ด๋ ธํ ์ด์ ์ ์ง์ ํด์ฃผ๊ณ Given-When-Then ๋ฐฉ์์ ํ์ฉํ์ฌ ํ ์คํธ ์ฝ๋๋ฅผ ์์ฑํด์ค๋๋ค.
- Given
UUID storeId = UUID.randomUUID();
UUID productId = UUID.randomUUID();
Store mockStore = new Store();
mockStore.setStoreId(storeId);
Product mockProduct = new Product();
mockProduct.setProductId(productId);
mockProduct.setProductName("๋ธ๊ธฐ ์ผ์ดํฌ");
mockProduct.setPrice(100);
mockProduct.setStore(mockStore);
when(productRepository.findById(productId)).thenReturn(Optional.of(mockProduct));
ํ ์คํธ๋ฅผ ์งํํ ๋ฐ์ดํฐ๋ฅผ ์ธํ ํด์ฃผ๋ ๊ฒ์ Given ์ด๋ผ๊ณ ํฉ๋๋ค.
when๋ฌธ์ ์ด์ฉํ์ฌ ํด๋น ํจ์๊ฐ ์คํ๋ ๋ ๋ฐํํ ๊ฐ์ ์ง์ ํฉ๋๋ค.
- When
boolean result = productServiceUnderTest.deleteProduct(productId);
ํ ์คํธ ๋์ ๋ฉ์๋๋ฅผ ํธ์ถํ๊ณ ๊ฒฐ๊ณผ๊ฐ์ ๋ฐ๋ ๊ณผ์ ์ When ์ด๋ผ๊ณ ํฉ๋๋ค.
- Then
assertTrue(result);
verify(productRepository, times(1)).findById(productId);
ํ ์คํธํ์ฌ ์ฆ๋ช ํ๋ ๊ณผ์ ์ Then ์ด๋ผ๊ณ ํฉ๋๋ค.
assertTrue(result); ๋ result ๊ฐ์ด true ์ด๋ฉด JUnit์ด ํ ์คํธ๋ฅผ ํต๊ณผ์ํต๋๋ค.
๋ง์ฝ์ result ๊ฐ์ด false ์ด๋ฉด ํ ์คํธ๊ฐ ์คํจํ์ฌ JUnit์์ AssertionError ๋ฅผ ๋ฐ์ ์ํต๋๋ค.
์ฐธ๊ณ ์ฌ์ดํธ
JUnit 5 User Guide
Although the JUnit Jupiter programming model and extension model do not support JUnit 4 features such as Rules and Runners natively, it is not expected that source code maintainers will need to update all of their existing tests, test extensions, and custo
junit.org
JUnit์ ์ด์ฉํ ๋จ์ ํ ์คํธ(Unit Test)
์ด๋ฏธ์ง ์ถ์ฒ(https://beststar-1.tistory.com/27๋จ์ ํ ์คํธ: ์๊ณ ๊ฒฉ๋ฆฌ๋ ์ ํ๋ฆฌ์ผ์ด์ ์ฝ๋ ๋ธ๋ก(์ผ๋ฐ์ ์ผ๋ก ํจ์ ๋๋ ๋ฉ์๋)์ ์ ํ์ฑ์ ํ์ธํ๋ ์ฝ๋ ๋ธ๋ก \[์ถ์ฒ]์ฆ, ์ฝ๋์ ์ต์ ๊ธฐ๋ฅ ๋จ์(๋ณดํต์
velog.io
JUnit์ผ๋ก ๋จ์ ํ ์คํธ ์ฝ๋ ๋ง๋ค๊ธฐ - ์ค์ ํธ
JUnit์ผ๋ก ๋จ์ ํ ์คํธ ์ฝ๋ ๋ง๋ค๊ธฐ - ์ค์ ํธ
velog.io
๋ฌธ์ ๊ฐ ์์ผ๋ฉด ๋๊ธ ๋จ๊ฒจ์ฃผ์ธ์ !
ํผ๋๋ฐฑ์ ์ธ์ ๋ ํ์์ ๋๋ค <3
'๐ฉ๐ปโ๐ป Dev' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Javascript] var, let, const ์ฐจ์ด์ ๊ณผ ํธ์ด์คํ (0) | 2025.02.27 |
---|---|
[Java] ์ ์ํ ๋นํธ ์ฐ์ฐ (0) | 2025.02.24 |
[Git] Git Clone, Fork (0) | 2025.02.18 |
[Git] Issue, Pull Request, Code Review ์ฌ์ฉํ์ฌ ํ์ (feat. PR ์น์ธ ํ ํด์ผํ ์ผ) (0) | 2025.02.15 |
[RESTful] RESTful ์๋น์ค๋? (0) | 2025.02.14 |