Mockito’s ArgumentCaptor
ArgumentCaptor는 Mockito 테스팅 프레임워크의 일부로, 메서드 호출에 사용된 인자를 캡처하는 데 사용됩니다.
이를 통해 해당 인자가 어떤 값으로 설정되었는지 테스트 내에서 확인할 수 있습니다.
Step 1: Import ArgumentCaptor
Java에서 ArgumentCaptor를 사용하려면 다음과 같이 import 해야합니다.
import org.mockito.ArgumentCaptor;
Step 2: Create an ArgumentCaptor Instance
캡처할 인자의 타입에 따라 ArgumentCaptor의 인스턴스를 생성합니다.
예를 들어, Long 타입의 인자를 캡처하려면 다음과 같이 작성합니다.
ArgumentCaptor<Long> captor = ArgumentCaptor.forClass(Long.class);
Step 3: Use verify with capture
Mock 객체에서 메서드가 호출될 때 캡처할 인자를 지정합니다.
verify(mockObject).someMethod(captor.capture());
Step 4: Retrieve the Captured Value
캡처된 값을 가져옵니다.
Type capturedValue = captor.getValue();
Example
아래는 실제 코드에서 ArgumentCaptor를 어떻게 사용하는지 보여주는 예시입니다.
import static org.mockito.Mockito.*;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.api.Test;
public class SomeClassTest {
@Mock
private SomeClass someClass;
@Test
public void testMethod() {
// Given
ArgumentCaptor<Long> captor = ArgumentCaptor.forClass(Long.class);
// When
someClass.someMethod(100L);
// Then
verify(someClass).someMethod(captor.capture());
Long capturedValue = captor.getValue();
System.out.println("Captured value: " + capturedValue); // Output will be "Captured value: 100"
}
}
이 예시에서 someMethod는 SomeClass에 정의된 메서드이며, Long 타입의 인자를 하나 받습니다.
ArgumentCaptor는 이 인자를 캡처하고, 캡처된 값은 capturedValue에 저장됩니다.
이 값을 테스트에서 사용하거나 콘솔에 출력할 수 있습니다.
왜 verify에 ArgumentCaptor의 caputre 값이 들어간 걸까
// Then
verify(someClass).someMethod(captor.capture());
Long capturedValue = captor.getValue();
verify와 ArgumentCaptor는 서로 다른 목적으로 사용되지만, 종종 함께 사용됩니다.
verify
verify 메서드는 Mockito에서 mock 객체의 특정 메서드가 어떻게 호출되었는지 검증하는 데 사용됩니다.
예를 들어, 특정 메서드가 정확히 한 번 호출되었는지, 아니면 특정 인자와 함께 호출되었는지 등을 검증할 수 있습니다.
verify(mockObject).someMethod(100L);
ArgumentCaptor
ArgumentCaptor는 메서드 호출 시 전달된 인자를 캡처하기 위해 사용됩니다.
이는 메서드가 어떤 인자로 호출되었는지 검증하거나, 이 인자를 다시 사용해야 할 때 유용합니다.
ArgumentCaptor<Long> captor = ArgumentCaptor.forClass(Long.class);
verify와 ArgumentCaptor의 조합
verify와 ArgumentCaptor를 함께 사용하면, mock 객체의 메서드가 특정 방식으로 호출되었는지 검증하면서 동시에 그 메서드에 전달된 인자를 캡처할 수 있습니다.
verify(mockObject).someMethod(captor.capture());
이렇게 하면 someMethod가 호출되었는지 확인할 수 있고, 만약 호출되었다면 captor가 그 호출에서 사용된 인자를 캡처합니다.
캡처된 인자는 나중에 captor.getValue()를 통해 가져와 다른 검증이나 연산에 사용할 수 있습니다.
'프로젝트 > 카카오 테크 캠퍼스' 카테고리의 다른 글
| initializationError Failed 오류 해결 (0) | 2023.12.12 |
|---|---|
| 크램폴린 IDE - NGINX 문제 해결 (1) | 2023.12.10 |
| 카카오 테크 캠퍼스 3단계 3주차 회고 (0) | 2023.09.20 |
| 카카오 테크 캠퍼스 3단계 2주차 회고 (0) | 2023.09.17 |
| 🐥 카카오 테크 캠퍼스 아이디어톤 지극히 개인적인 후기 (1) | 2023.08.27 |
댓글