-
[TDD] @SpyTDD 2024. 9. 1. 01:33
The Spy is a wrapper created on an actual instance of the object that lets you call the real methods of that object unless the method is stubbed.
It is based on the concept of partial mocking, where you want to test some real methods and mock only a few methods in a class.
Spy 객체는 껍데기만 있는 Mock 객체와 다르게 실제로 구현된 기능이 돌아가는 객체이다.
Spy 객체의 일부 기능을 Mock 객체처럼 Stub할 수 있다.
public class SpyWithAnnotationTest{ @Spy List<String> spyList = new LinkedList<String>(); @Test public void testSpyOnList() { // Real Method Call spyList.add("one"); spyList.add("two"); // size() method is stubbed to return 50 doReturn(50).when(spyList).size(); // Output - "one" System.out.println(spyList.get(0)); // Output 50 , since the stubbed method is invoked System.out.println(spyList.size()); } }
[@Spy 객체도 Mock 객체이다]
중요한 것은 @Spy도 Mock 객체의 일종이라는 것이다
하지만 stubbing을 안한 메서드에 대해서는 실제로 동작해야하기 때문에 new를 통해 객체를 생성해줘야한다
객체를 생성하지 않으면 null pointer exception이 뜬다
그리고 Mock 객체의 일종이므로
@InjectMocks으로 선언된 Mock객체에 자동으로 주입이 된다
'TDD' 카테고리의 다른 글
[TDD] @Ignore @Disabled (0) 2024.09.11 [TDD] @DataJpaTest (1) 2024.09.10 [TDD] @Mock vs @MockBean (0) 2024.08.31 [TDD] Mockito annotations.zip (0) 2024.08.31 [TDD] @WebMvcTest vs MockMvcBuilders.standaloneSetup (0) 2024.08.31