(+) 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