hello world

ArgumentCaptor 본문

WEB/Junit

ArgumentCaptor

sohyun_92 2025. 5. 18. 21:44

ArgumentCaptor

ArgumentCaptor는 Mockito 테스팅 프레임워크의 일부로 메서드 호출에 사용된 인자를 캡처하는 데 사용됨
이를 통해 해당 인자가 어떤 값으로 설정되었는지 테스트 내에서 확인할 수 있다.

이것은 테스트하려는 메서드 외부의 인수에 액세스할 수 없을 때 특히 유용하다

* 메소드에 인자로 받기 전에 해당 값을 중간에 값을 받아 검증하고 싶을 때가 있다 그것을 수행해주는 것이 바로 ArgumentCeptor

 

ArgumentCaptor 사용 예제 코드

  StudentScore expectStudentScore =  StudentScoreFixture.passed();

  StudentPass expectStudentPass = StudentPass.builder()
                .studentName(expectStudentScore.getStudentName())
                .exam(expectStudentScore.getExam())
                .avgScore((new MyCalculator(0.0))
                .add(expectStudentScore.getKorScore().doubleValue())
                .add(expectStudentScore.getEnglishScore().doubleValue())
                .divide(2.0)
                .getResult()
         ).build();


        ArgumentCaptor<StudentScore> studentScoreArgumentCaptor = ArgumentCaptor.forClass(StudentScore.class);
        // 먼저 캡쳐 할 인자의 클래스를 가지고 ArgumentCaptor을 생성한다.
        
        
        studentScoreService.saveScore(
                expectStudentScore.getStudentName(),
                expectStudentScore.getExam(),
                expectStudentScore.getKorScore(),
                expectStudentScore.getEnglishScore()
        );

        //then
        Mockito.verify(studentScoreRepository,Mockito.times(1)).save(studentScoreArgumentCaptor.capture()); //1번 실행이 되어야함
        StudentScore capturedStudentScore = studentScoreArgumentCaptor.getValue();

        Assertions.assertEquals(expectStudentScore.getStudentName(),capturedStudentScore.getStudentName());
        Assertions.assertEquals(expectStudentScore.getExam(),capturedStudentScore.getExam());
        Assertions.assertEquals(expectStudentScore.getKorScore(),capturedStudentScore.getKorScore());

 


ArgumentCaptor<StudentScore> studentScoreArgumentCaptor = ArgumentCaptor.forClass(StudentScore.class);

-ArgumentCaptor<StudentScore> = ArgumentCaptor.forClass(StudentScore.class);

StudentScore 객체를 캡처하기 위한 ArgumentCaptor를 생성한다.

이는 후에 save 메소드에 전달된 StudentScore 객체를 검증할 때 사용된다.


Mockito.verify(studentScoreRepository,Mockito.times(1)).save(studentScoreArgument.capture()); //1번 실행이 되어야함

-Mockito를 사용하여 studentScoreRepository의 save 메소드가 1번 호출되었는지를 검증한다.

동시에 Answer 객체를 studentScoreArgument에 캡처한다.

 

*verify와 ArgumentCaptor를 함께 사용하면, mock 객체의 메서드가 특정 방식으로 호출되었는지 검증하면서 동시에 그 메서드에 전달된 인자를 캡처할 수 있습니다

 


*ArgumentCaptor에서 쓰이는 메서드는 크게 두 가지 인데,

  1. capture() : 해당 메서드의 인자로 들어가는 객체를 캡쳐해 ArgumentCaptor로 감싸서 갖고 있는다.
  2. getValue() : capture()로 캡쳐한 ArgumentCaptor 객체에서 인자 객체를 추출한다.
StudentScore capturedStudentScore = studentScoreArgument.getValue();

capturedStudentScore를 사용하여 save 메소드에 전달된 StudentScore객체를 가져온다.

 


Assertions.assertEquals(expectStudentScore.getEnglishScore(),capturedStudentScore.getEnglishScore());

저장된 StudentScore객체의 EnglishScore 속성이 예상한 expectStudentScore 객체와 일치하는지 검증한다.

Comments