(+) Spy vs Mock
Spy์ Mock ์ ๋ค๋ฅด๋ค
๊ตณ์ด ์กฐ์ ๋น์ฉ์ ์น๋ฅด๊ณ ํ ์คํธ๋ฅผ ์ํ ์กฐ์์ ํ๋ค๋ฉด Spy ๋ ํ์ฉํ๊ธฐ ์ข๋ค. Spy๋ ์ค์ ๊ฐ์ฒด์ ์ค์ ๋ฉ์๋ ํธ์ถ์ด ๋ฐ์๋๊ณ Mock ์ ๋ฆฌ์ผํ ๊ป๋ฐ๊ธฐ๋ค.
์คํ์ค๋ฒํ๋ก์ฐ์ ๋ต๋ณ์ค ์ง๊ด์ ์ธ ์ค๋ช ์ ํด๋ ๊ฒ์ด ์์ด ์ฎ๊ฒจ์๋ค.
Technically speaking both "mocks" and "spies" are a special kind of "test doubles".
Mockito is unfortunately making the distinction weird.
A mock in mockito is a normal mock in other mocking frameworks (allows you to stub invocations; that is, return specific values out of method calls).
A spy in mockito is a partial mock in other mocking frameworks (part of the object will be mocked and part will use real method invocations).
mock ์ mock ์ด๊ณ , spy ๋ ๋ถ๋ถ์ ์ธ mock ์ด๋ค.
์์ ์ฝ๋
์๋ ์ํ ์ฝ๋๋ฅผ ๋ณด์. ๋ฌผ๋ก ์ ๋ถ ํต๊ณผํ๋ ์ฝ๋๋ค.
@SpringBootTest
public class SampleTest {
@Test
void spyAndMockTest() {
User spyUser = Mockito.spy(new User("kim", 1));
Mockito.doReturn("king").when(spyUser).getName();
Assertions.assertThat(spyUser.getName()).isEqualTo("king");
Assertions.assertThat(spyUser.getGrade()).isEqualTo(1);
User mockUser = Mockito.mock(User.class);
Assertions.assertThat(mockUser).isNotNull();
Assertions.assertThat(mockUser.getName()).isNull();
}
}
public class User {
private String name;
private int grade;
public User(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public int getGrade() {
return grade;
}
}
์๋ ์ฝ๋์์๋ ์ ์ ์๋ฏ์ด spy ๋ก ํ๋ฒ ๊ฐ์ผ mockList๊ฐ ์ค์ ๋ก add(100), add(200) ์ ํธ์ถ ํ์์ ์ ์ ์๋ค. ํ์ง๋ง Stubbing ์ญ์ ์ ๋์ํ๊ณ ์์์ ๋ณด์ฌ์ฃผ๊ณ ์๋ค.
@Test
public void SPY_SAMPLE_TEST(){
List<Integer> list = new ArrayList<Integer>();
List<Integer> mockList = Mockito.spy(list);
mockList.add(100);
assertEquals(mockList.size(),1); // PASS
doReturn(5).when(mockList).size(); // Stubbing
assertEquals(mockList.size(),5); // PASS
mockList.add(200);
assertEquals(mockList.size(),5); // PASS
System.out.println(mockList); // [100, 200]
verify(mockList,times(2)).add(anyInt()); // PASS
}
Last updated