source

@RunWith(Mockito)JUnitRunner.class)와 MockitoAnnotations.initMocks(이것)

itover 2022. 12. 31. 16:37
반응형

@RunWith(Mockito)JUnitRunner.class)와 MockitoAnnotations.initMocks(이것)

새로운 jUnit4 테스트를 작성하면서@RunWith(MockitoJUnitRunner.class)또는MockitoAnnotations.initMocks(this).

새로운 테스트를 작성하면 마법사가 자동으로 Runner를 사용하여 테스트를 생성합니다.모키토용 자바독JUnitRunner는 다음과 같이 기술합니다.

JUnit 4.4 이상과 호환되는 이 러너는 다음과 같은 동작을 추가합니다.

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

Runner를 사용하는 것이 다음보다 유리한지 확실하지 않습니다.initMocks()사용하던 방식입니다.

MockitoJUnitRunner프레임워크 사용현황 자동검증 및 자동검증을 제공합니다.initMocks().

프레임워크 사용의 자동 검증은, 실제로 실시할 가치가 있습니다.이러한 실수 중 하나를 하면 더 나은 보고를 할 수 있습니다.

  • 스태틱이라고 부릅니다.whenmethod, 단, stubbing을 매칭하여 완료하지 마십시오.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가 정확히 지적한 것처럼 스프링과 같은 다른 JUnit 러너가 필요하다면 사용할 수 없습니다.

이제 제 추천이 바뀌었습니다.제가 이 답변을 처음 썼을 때부터 Mockito 팀은 새로운 기능을 추가했습니다.이것은 JUnit 규칙입니다.이것은 JUnit와 완전히 같은 기능을 수행합니다.MockitoJUnitRunner하지만 다른 주자들의 사용을 방해하지 않기 때문에 더 좋다.

포함하다

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

츠키노 하면 이 자동화됩니다.은 마치 '모크'와 .MockitoJUnitRunner 하지만 은 '아예'를 해도 됩니다.SpringJUnit4ClassRunnerJUnitRunner를 소개합니다.Mockito 2.1.0 이후에는 보고되는 문제의 종류를 정확하게 제어하는 추가 옵션이 있습니다.

runner는 불필요)을할 수 .@Before메서드).한편, 러너를 사용할 수 없는 경우도 있습니다.즉, 이미 러너를 사용하고 있는 경우 등입니다.

바로 그겁니다.그것은 단지 선호의 문제이다.

언급URL : https://stackoverflow.com/questions/10806345/runwithmockitojunitrunner-class-vs-mockitoannotations-initmocksthis

반응형