- ์ด์ ๊ธ ํ์ธ -
1. Mockito
- ๋จ์ ํ
์คํธ๋ฅผ ์ํด ๋ชจ์ ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ณ ๊ด๋ฆฌํ๋ ๋ฐ ์ฌ์ฉ๋๋ Java ์คํ์์ค ํ๋ ์์ํฌ๋ฅผ ์๋ฏธํฉ๋๋ค.
- ์ค์ ๊ฐ์ฒด์ ๋์์ ๋ชจ๋ฐฉํ๋ ๋ชจ์ ๊ฐ์ฒด(Mock Object)๋ฅผ ์์ฑํ์ฌ ์ฝ๋์ ‘ํน์ ๋ถ๋ถ์ ๊ฒฉ๋ฆฌ’์ํค๊ณ ํ
์คํธํ๊ธฐ ์ฝ๊ฒ ๋ง๋ค์ด์ค๋๋ค.
- Mockito ๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด์๋ ์๋์ ๊ฐ์ด gradle์ ์์กด์ฑ์ ์ถ๊ฐํด ์ฃผ์ด์ผ ํฉ๋๋ค.
dependencies {
....
testImplementation "org.mockito:mockito-core:3.+"
...
}
2. ์กฐ๊ฑด์ ๋ฐ๋ฅธ ๋ฉ์๋ ํธ์ถ ์ฌ๋ถ ํ์ธ
- studentScoreService.saveScore... 3-2 ํธ์์ ๋ง๋ ๋ฉ์๋๋ฅผ ๊ฒ์ฆํ๋ ์์ ์ ์ํํ๊ฒ ์ต๋๋ค.
- ์ฐธ์กฐ -
1) saveScoreMockTest
- ์ฑ์ ์ ์ฅ ๋ก์ง ๊ฒ์ฆ / 60์ ์ด์์ธ ๊ฒฝ์ฐ
@Test
@DisplayName("์ฑ์ ์ ์ฅ ๋ก์ง ๊ฒ์ฆ / 60์ ์ด์์ธ ๊ฒฝ์ฐ")
public void saveScoreMockTest() {
// given : ํ๊ท ์ ์๊ฐ 60์ ์ด์์ธ ๊ฒฝ์ฐ
StudentFailRepository studentFailRepository = Mockito.mock(StudentFailRepository.class);
StudentScoreRepository studentScoreRepository = Mockito.mock(StudentScoreRepository.class);
StudentPassRepository studentPassRepository = Mockito.mock(StudentPassRepository.class);
StudentScoreService studentScoreService = new StudentScoreService(
studentFailRepository,
studentScoreRepository,
studentPassRepository
);
String givenStudentName = "pcy";
String givenExam = "testexam";
Integer givenKorScore = 80;
Integer givenEnglishScore = 100;
Integer givenMathScore = 60;
// when
studentScoreService.saveScore(
givenStudentName,
givenExam,
givenKorScore,
givenEnglishScore,
givenMathScore
);
// then
Mockito.verify(studentScoreRepository, Mockito.times(1)).save(Mockito.any());
Mockito.verify(studentPassRepository, Mockito.times(1)).save(Mockito.any());
Mockito.verify(studentFailRepository, Mockito.times(0)).save(Mockito.any());
}
- ํ๊ท ์ ์๊ฐ 60์ ์ด์์ธ ๊ฒฝ์ฐ
studentScoreRepository, studentPassRepository๋ฅผ ์ฐจ๋ก๋ก ํธ์ถ์ ํ์ฌ์ผ ํฉ๋๋ค.
- studentScoreService.saveScore ๋ก์ง์ ์๋ ๊นํ ์ฃผ์๋ฅผ ์ฐธ์กฐํด์ฃผ์๋ฉด ๋ ๊ฑฐ ๊ฐ์ต๋๋ค.
- then ๋ถ๋ถ์์ ํธ์ถํ๋
Mockito.verify(studentScoreRepository, Mockito.times(1)).save(Mockito.any());
Mockito.verify(studentPassRepository, Mockito.times(1)).save(Mockito.any());
Mockito.verify(studentFailRepository, Mockito.times(0)).save(Mockito.any());
Mockito์ ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ํ ์คํธ๋ฅผ ํ๋ฉด ๋ฉ๋๋ค.
- ์ ์์ผ ๊ฒฝ์ฐ ์๋์ ๊ฐ์ ๊ฒฐ๊ณผ๋ฅผ ํ์ธ ํ ์ ์์ต๋๋ค.
- ๋ง์ฝ ํธ์ถ ํ์๋ฅผ ๋ค๋ฅด๊ฒ ์ค์ ํ๊ฑฐ๋ ํ ์คํธ ํด์ผ ํ๋ ๋ก์ง์ด ์๋ชป๋์๋ค๋ฉด ์๋์ ๊ฐ์ ๊ฒฐ๊ณผ๋ฅผ ํ์ธํ ์ ์์ต๋๋ค.
2) ์ฐธ์กฐ Mockito ๋ฉ์๋ ์ค๋ช
[1] verify()
verify() ๋ฉ์๋๋ Mockito ๋ผ์ด๋ธ๋ฌ๋ฆฌ์์ ์ ๊ณตํ๋ ์ค์ํ ๋ฉ์๋ ์ค ํ๋์ ๋๋ค. ์ด ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ํ ์คํธ ์ค์ ๋ชจ์ ๊ฐ์ฒด์์ ์ํธ์์ฉ์ ๊ฒ์ฆํ ์ ์์ต๋๋ค. ์ฆ, ๋ฉ์๋๊ฐ ์์๋๋ก ํธ์ถ๋์๋์ง, ํธ์ถ ํ์๊ฐ ๋ง๋์ง, ํธ์ถ ์์๊ฐ ๋ง๋์ง ๋ฑ์ ํ์ธํ ์ ์์ต๋๋ค.
[2] times()
times() ๋ฉ์๋๋ ํน์ ๋ชจ์ ๊ฐ์ฒด(mock object)์ ๋ฉ์๋ ํธ์ถ ํ์๋ฅผ ๊ฒ์ฆํ๋๋ฐ ์ฌ์ฉ๋๋ ๋ฉ์๋์ ๋๋ค. ํ ์คํธ ์ค์ ๋ชจ์ ๊ฐ์ฒด์ ์ํธ์์ฉ์ด ์์๋๋ก ์ด๋ฃจ์ด์ง๋์ง๋ฅผ ํ์ธํ๋๋ฐ ์ ์ฉํฉ๋๋ค. times() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ๋ฉ์๋ ํธ์ถ ํ์๋ฅผ ์ ํํ๊ฒ ๊ฒ์ฆํ ์ ์์ต๋๋ค.
3. Github์ผ๋ก ํ์ธ
์ ์ฒด ํ์ผ ํ์ธ(ํ์ฌ ๋ณ๊ฒฝ๋ด์ญ)
[Github]
์ฐธ์กฐ : ์ธํ๋ฐ ๊ฐ์ [์ฅฌ์ฅฌ์ ํจ๊ป ํ๋ฃจ๋ง์ ๋๋ด๋ ์คํ๋ง ํ ์คํธ]