mock과 spy

Haechan Kim·2024년 2월 20일
0

Spring

목록 보기
61/68

mock과 spy

mock

mock 객체는 해당 클래스의 행동(behavior) 가지지 못함.
직접 지정하지 않으면 (when(), thenReturn()) 수행하는 모든 행동은 디폴트 값.

@Test
public void withoutSpying() {
    ArrayList<String> mockList = mock(ArrayList.class);

    System.out.println(mockList.get(0));  // null
    System.out.println(mockList.size());  // 0

    mockList.add("Test String 1");  // 영향 없음
    mockList.add("Test String 2");

    System.out.println(mockList.size());  // 0

    when(mockList.size()).thenReturn(5);
    System.out.println(mockList.size());  // 5
}

spy

spying은 지정한 클래스의 행동 그대로 갖는다.
when() 등으로 직접 지정하지 않아도 됨.
지정한다면 기존 행동 재정의하게 됨.

@Test
public void spying() {
    ArrayList<String> spyList = spy(ArrayList.class);

    //System.out.println(spyList.get(0));  // IndexOutOfBoundsException
    System.out.println(spyList.size());  // 0

    spyList.add("Test String 1");
    spyList.add("Test String 2");

    System.out.println(spyList.size());  // 2
    System.out.println(spyList.get(0));  // Test String 1
    System.out.println(spyList.get(1));  // Test String 2

    when(spyList.size()).thenReturn(10);  // 행동 재정의
    System.out.println(spyList.size());  // 10
}

mock은 가짜 오브젝트 이지만 spy는 진짜 오브젝트.
spy 쓰는 이유는?
-> mock과 달리 stub이 필요한 부분에만 할 수 있기 때문.

stub : 해당 메소드(or 필드) 호출했을 때 반환값 미리 지정하는 것.

0개의 댓글