[java] @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 실행기가 필요한 경우 사용할 수 없습니다.

이제 내 추천이 변경되었습니다. Mockito 팀은이 답변을 처음 작성한 이후로 새로운 기능을 추가했습니다. .NET Framework와 정확히 동일한 기능을 수행하는 JUnit 규칙 MockitoJUnitRunner입니다. 그러나 다른 주자의 사용을 배제하지 않기 때문에 더 좋습니다.

포함

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

시험 수업에서. 이것은 모의를 초기화하고 프레임 워크 유효성 검사를 자동화합니다. 그렇습니다 MockitoJUnitRunner. 하지만 이제는 SpringJUnit4ClassRunner또는 다른 JUnitRunner도 사용할 수 있습니다 . Mockito 2.1.0부터는보고되는 문제의 종류를 정확하게 제어하는 ​​추가 옵션이 있습니다.


답변

러너를 사용하면 약간의 코딩을 절약 할 수 있습니다 ( @Before방법이 필요 없음 ). 반면에 러너를 사용하는 것은 때때로 불가능합니다. 즉, 이미 SpringJUnit4ClassRunner.

그게 다야. 그것은 단지 선호도의 문제입니다.


답변