developer tip

@RunWith (MockitoJUnitRunner.class) 대 MockitoAnnotations.initMocks (this)

optionbox 2020. 8. 22. 08:41
반응형

@RunWith (MockitoJUnitRunner.class) 대 MockitoAnnotations.initMocks (this)


새로운 jUnit4 테스트를 작성하는 동안 @RunWith (MockitoJUnitRunner.class) 또는 MockitoAnnotations.initMocks (this) 를 사용할지 궁금합니다 .

새 테스트를 만들었고 마법사는 Runner로 테스트를 자동으로 생성했습니다. MockitoJUnitRunner 용 Javadocs는 다음과 같이 설명합니다.

JUnit 4.4 이상과 호환되는이 실행기는 다음 동작을 추가합니다.

Mock으로 주석이 달린 모의를 초기화하므로 MockitoAnnotations.initMocks (Object)를 명시 적으로 사용할 필요가 없습니다. 모의는 각 테스트 방법 전에 초기화됩니다. 각 테스트 방법 후에 프레임 워크 사용을 검증합니다.

Runner를 사용하는 것이 내가 과거에 사용 했던 initMocks () 메서드 보다 이점이 있는지 여부는 분명하지 않습니다 .

어떤 생각이나 링크라도 감사하겠습니다!


MockitoJUnitRunner프레임 워크 사용에 대한 자동 유효성 검사와 자동 initMocks().

프레임 워크 사용에 대한 자동 유효성 검사는 실제로 가치가 있습니다. 이러한 실수 중 하나를 범하면 더 나은보고를 할 수 있습니다.

  • 당신은 정적 호출 when방법을하지만, 일치와 스터 빙을 완료하지 않는 thenReturn, thenThrow또는 then. (아래 코드의 오류 1)

  • verify모의를 호출 하지만 확인하려는 메서드 호출을 제공하는 것을 잊었습니다. (아래 코드의 오류 2)

  • 당신은 전화 when후 방법을 doReturn, doThrow또는 doAnswer및 모의을 통과,하지만 당신은 스텁하려고하는하는 방법을 제공하는 것을 잊지. (아래 코드의 오류 3)

프레임 워크 사용에 대한 유효성 검사가없는 경우 Mockito 메서드를 다음과 같이 호출 할 때까지 이러한 실수가보고되지 않습니다 . 이것은

  • 동일한 테스트 방법 (아래 오류 1과 같음)에서
  • 다음 테스트 방법 (아래 오류 2와 같음)에서
  • 다음 시험 수업에서.

실행 한 마지막 테스트에서 발생하는 경우 (아래의 오류 3과 같이) 전혀보고되지 않습니다.

이러한 각 유형의 오류가 표시되는 방식은 다음과 같습니다. 여기에서 JUnit이 여기에 나열된 순서대로 이러한 테스트를 실행한다고 가정합니다.

@Test
public void test1() {

    // ERROR 1
    // This compiles and runs, but it's an invalid use of the framework because 
    // Mockito is still waiting to find out what it should do when myMethod is called.
    // But Mockito can't report it yet, because the call to thenReturn might 
    // be yet to happen.
    when(myMock.method1());

    doSomeTestingStuff();

    // ERROR 1 is reported on the following line, even though it's not the line with
    // the error.
    verify(myMock).method2();

}

@Test
public void test2() {

    doSomeTestingStuff();

    // ERROR 2
    // This compiles and runs, but it's an invalid use of the framework because
    // Mockito doesn't know what method call to verify.  But Mockito can't report 
    // it yet, because the call to the method that's being verified might 
    // be yet to happen.
    verify(myMock);
}

@Test
public void test3() {

    // ERROR 2 is reported on the following line, even though it's not even in 
    // the same test as the error.
    doReturn("Hello").when(myMock).method1();


    // ERROR 3
    // This compiles and runs, but it's an invalid use of the framework because
    // Mockito doesn't know what method call is being stubbed.  But Mockito can't 
    // report it yet, because the call to the method that's being stubbed might 
    // be yet to happen.

    doReturn("World").when(myMock);

    doSomeTestingStuff(); 

    //  ERROR 3 is never reported, because there are no more Mockito calls. 
}

5 년 전에 처음이 답변을 썼을 때

그래서 MockitoJUnitRunner가능한 한 사용을 권장 합니다. 그러나 Tomasz Nurkiewicz가 올바르게 지적했듯이 Spring과 같은 다른 JUnit 실행기가 필요한 경우 사용할 수 없습니다.

My recommendation has now changed. The Mockito team have added a new feature since I first wrote this answer. It's a JUnit rule, which performs exactly the same function as the MockitoJUnitRunner. But it's better, because it doesn't preclude the use of other runners.

Include

@Rule 
public MockitoRule rule = MockitoJUnit.rule();

in your test class. This initialises the mocks, and automates the framework validation; just like MockitoJUnitRunner does. But now, you can use SpringJUnit4ClassRunner or any other JUnitRunner as well. From Mockito 2.1.0 onwards, there are additional options that control exactly what kind of problems get reported.


Using runner lets you save a little bit of coding (no need for @Before method). On the other hand using a runner is sometimes not possible, i.e. when you are already using one, like SpringJUnit4ClassRunner.

That's it. It is just a matter of preference.

참고URL : https://stackoverflow.com/questions/10806345/runwithmockitojunitrunner-class-vs-mockitoannotations-initmocksthis

반응형