[java] Mockito.any ()는 제네릭과 인터페이스를 전달합니다.

제네릭으로 인터페이스 유형을 전달할 수 있습니까?

인터페이스 :

public interface AsyncCallback<T>

내 테스트 방법에서 :

Mockito.any(AsyncCallback.class)

미루 <ResponseX>거나하지 .class않았다.



답변

형식에 안전한 방법이 있습니다. 다음 ArgumentMatchers.any()과 같이 형식을 사용 하고 정규화하십시오.

ArgumentMatchers.<AsyncCallback<ResponseX>>any()


답변

Java 8을 사용 any()하면 향상된 유형 유추로 인해 인수 또는 유형 매개 변수없이 간단하게 정적 가져 오기 를 사용할 수 있습니다 . 컴파일러는 이제 대상 유형 (메소드 인수의 유형)에서 실제로 의미하는 것을 알았습니다 Matchers.<AsyncCallback<ResponseX>>any(). 이것은 Java 8 이전의 솔루션입니다.


답변

제네릭을 허용하려면 다음과 같은 메커니즘을 채택해야했습니다.

import static org.mockito.Matchers.any;
List<String> list = any();
when(callMyMethod.getResult(list)).thenReturn(myResultString);

이것이 누군가를 돕기를 바랍니다.


답변

pierrefevrier 의견을 답변으로 게시하면 댓글 대신 답변에있는 경우 유용 할 수 있습니다.

Mockito의 새로운 버전 : (Matchers.<AsyncCallback<ResponseX>>any()


답변

thSoft의 답변에 덧붙여 메소드에서 any ()에 대한 한정된 호출을하는 것은 반환 유형이 유추를 허용했기 때문에 자격을 제거 할 수 있음을 의미했습니다.

private HashMap<String, String> anyStringStringHashMap() {
    return Matchers.any();
}


답변

원하는 경우 억제 경고를 추가하여 캐스트 할 수 있습니다.

@SuppressWarnings("unchecked")
AsyncCallback<ResponseX> callback = Mockito.any(AsyncCallback.class)

Java가 ‘generic’제네릭을 허용하면 다음과 같은 방법을 사용할 수 있습니다.

private static <T, E> T<E> mock(Class<T<E>> clazz)


답변

Spring을 사용하여 비슷한 문제가 발생했습니다 Example.

Mockito.when(repo.findAll(Mockito.<Example<SrvReqToSupplierComment>>any()))
            .thenReturn(Lists.emptyList());

여기서, b / c findAll 메소드는 규정을 사용해야 Sort하고 and와 같은 여러 유형을 사용할 수 있습니다 Iterable. Mockito.any(Example.class)유형 안전 경고와 함께 사용할 수도 있습니다 .