ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Junit5] org.mockito.exceptions.misusing.MissingMethodInvocationException
    트러블 슈팅 2022. 11. 21. 23:11

    AuthService 단위 테스트를 작성하던 도중 JwtTokenUtils 내부의 static method를 mocking하고 테스트를 진행하니 다음과 같은 에러가 발생하였다.

    org.mockito.excptions.misusing.MissingMethodInvocationException:
    when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles); Also, this error might show up because:
    1. you stub either of: final/private/equals()/hashCode() methods. Those methods *cannot* be stubbed/verified. Mocking methods declared on non-public parent classes is not supported.
    2. inside when() you don't call method on mock but on some other object.

    static method를 일반 method와 같이 mocking하여 테스트를 진행하면 만날 수 있는 오류이다.

     

    해결 방법

    1. build.gradle에 다음과 같은 dependency를 추가한다.

    testImplementation group: 'org.mockito', name: 'mockito-inline', version: '4.9.0'

     

    2. 테스트 코드에서 mackStatic()을 사용한다.

    @Test
    void 로그인_정상_작동() {
        String username = "username";
        String password = "password";
    
        jwtTokenUtilsMockedStatic = mockStatic(JwtTokenUtils.class); // mockStatic 사용
    
        when(memberService.findByUsername(username)).thenReturn(Member.of(username, password));
        when(passwordEncoder.matches(password, password)).thenReturn(true);
        when(generateToken(username, null, null)).thenReturn("test-token");
        Assertions.assertDoesNotThrow(() -> authService.login(username, password));
    
        jwtTokenUtilsMockedStatic.close(); // close 호출
    }
    • mockstatic()에 static method가 존재하는 Class를 넣어준다.
    • 한 스레드에서 staticMocking은 한 번밖에 등록되지 않기 때문에, 반드시 종료 전 close() 메서드를 호출해야 한다.

     

    위 방법을 적용하면 테스트가 성공적으로 완료되는 것을 확인할 수 있다.

    댓글

Designed by Tistory.