Study/Spring Boot

SpringBoot(3) MockitoAnnotations.initMocks Deprecated

Nullsector_1 2021. 5. 18. 15:51

개발 환경 : JAVA 1.8 / Spring Boot 2.4.1 / Gradle 6.7.1 / MySql

IDE : IntelliJ 20.3.3

Dependency : spring-boot-starter-test:2.4.1 or mockito-all:1.10.19

 

 

저번에 공부했던 Mockito를 오늘 추가적으로 공부하려고 프로젝트를 켜보니

이렇게 .initMocks 에 취소선이 생기고 @Deprecated 선언이 되어있었다.

이게 뭔일이여.. 하고 찾아보니 Mockito-core 3.4.0 api 이상부터는

.initMocks는 deprecated 되고 대신 .openMocks 라는 메소드를 사용하라고 한다.

 

javadoc Mockito 문서 - MockitoAnnotations

 

 

 

대충 initMocks는 이제 사용되지 않으니까 대신 openMocks를 사용해라. 얘는 자동으로 close도 해주는 쩌는 애다.

란 내용인 것 같다.

 

MockitoAnnotations 클래스도 까보니 이렇게 되어있다.

...
public class MockitoAnnotations {

    ...
    
    public static AutoCloseable openMocks(Object testClass) {
        if (testClass == null) {
            throw new MockitoException(
                    "testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations class");
        }

        AnnotationEngine annotationEngine =
                new GlobalConfiguration().tryGetPluginAnnotationEngine();
        return annotationEngine.process(testClass.getClass(), testClass);
    }

   ...
   
    @Deprecated
    public static void initMocks(Object testClass) {
        try {
            openMocks(testClass).close();
        } catch (Exception e) {
            throw new MockitoException(
                    join(
                            "Failed to release mocks",
                            "",
                            "This should not happen unless you are using a third-part mock maker"),
                    e);
        }
    }
}

 

결론

 

사실 .initMocks를 사용해도 mockito-core:3.6.28 버전 기준 아직 테스트는 정상작동 하고있다.

하지만 언제 완전 종료가 될 지 모르니 만약 프로젝트 개발환경이 mockito-core: 3.4.0 이상이면

권장사항인 .openMocks 를 사용하자