programing

이유: void가 mockito 사용에 적합하도록 유형 변수 T의 인스턴스가 존재하지 않습니다.

oldcodes 2023. 3. 10. 22:44
반응형

이유: void가 mockito 사용에 적합하도록 유형 변수 T의 인스턴스가 존재하지 않습니다.

void 메서드를 실행할 때 예외를 발생시키고 싶다.

when(booking.validate(any())).thenThrow(BookingException.builder().build());

컴파일 오류가 있습니다.

Required type: T
Provided: void
reason: no instance(s) of type variable(s) T exist so that void conforms to T

void 메서드를 사용하려면doThrow구문을 사용합니다.

고객의 경우는 다음과 같습니다.

doThrow(BookingException.builder().build())
      .when(booking)
      .validate(any());

정확한 구문을 알아냈어요

Service mockedService = new DefaultServie();
doNothing().when(mockedService).sendReportingLogs(null);

이것이 질문에 답하기를 바랍니다.

/**
 * Use <code>doThrow()</code> when you want to stub the void method with an exception.
 * <p>
 * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
 * does not like void methods inside brackets...
 * <p>
 * Example:
 *
 * <pre class="code"><code class="java">
 *   doThrow(new RuntimeException()).when(mock).someVoidMethod();
 * </code></pre>
 *
 * @param toBeThrown to be thrown when the stubbed method is called
 * @return stubber - to select a method for stubbing
 */
@CheckReturnValue
public static Stubber doThrow(Throwable... toBeThrown) {
    return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}

@Shane의 코멘트를 보완하는 것 뿐이지만, 그것은 생명을 구하기는 했지만 그다지 명확하지는 않았다.

저장소 메서드에서 Persistence Exception을 슬로우하는 방법의 예:

doThrow(new PersistenceException())
            .when(outboxRepository)
            .delete(isA(WorkersEphemeralOutboxEntry.class));

이것은 특히 메서드가 오버로드되어 있어 컴파일러가 any()로 호출해야 할 메서드를 특정할 수 없고 any(Class.class)에서 컴파일 오류가 발생할 때 도움이 됩니다.

언급URL : https://stackoverflow.com/questions/60977373/reason-no-instances-of-type-variables-t-exist-so-that-void-conforms-to-usin

반응형