programing

mockito 콜백 및 인수값 가져오기

bestcode 2022. 9. 25. 00:29
반응형

mockito 콜백 및 인수값 가져오기

Mockito가 함수 인수 값을 캡처할 수 없습니다!저는 검색 엔진 인덱스를 조롱하고 인덱스를 작성하는 대신 해시만 사용하고 있습니다.

// Fake index for solr
Hashmap<Integer,Document> fakeIndex;

// Add a document 666 to the fakeIndex
SolrIndexReader reader = Mockito.mock(SolrIndexReader.class);

// Give the reader access to the fake index
Mockito.when(reader.document(666)).thenReturn(document(fakeIndex(666))

쿼리 결과(즉, 반환되는 문서)를 테스트 중이므로 임의 인수를 사용할 수 없습니다.마찬가지로 특정 값을 지정하지 않고 각 문서에 대해 행을 지정합니다.

Mockito.when(reader.document(0)).thenReturn(document(fakeIndex(0))
Mockito.when(reader.document(1)).thenReturn(document(fakeIndex(1))
....
Mockito.when(reader.document(n)).thenReturn(document(fakeIndex(n))

모키토 사용 페이지의 콜백 섹션을 보았습니다.유감스럽게도 자바가 아니기 때문에 자바에서 동작할 수 있는 독자적인 해석을 얻을 수 없었습니다.

편집(구체적인 설명을 위해):어떻게 하면 Mockito가 X 인수를 캡처하여 제 함수에 전달할 수 있을까요?X의 정확한 값(또는 ref)을 함수에 전달하고 싶다.

모든 사례를 열거하는 것은 아니며, 쿼리마다 다른 결과를 테스트하기 때문에 임의 인수는 작동하지 않습니다.

[Mockito] 페이지에는 다음과 같이 되어 있습니다.

val mockedList = mock[List[String]]
mockedList.get(anyInt) answers { i => "The parameter is " + i.toString } 

그건 자바가 아니고 자바로 번역하는 법도 모르고 함수에 무슨 일이 있었는지도 모르겠어요.

모키토를 사용해 본 적은 없지만, 배우고 싶기 때문에, 이쪽입니다.나보다 덜 모르는 사람이 대답하면 먼저 대답부터 해봐!

Mockito.when(reader.document(anyInt())).thenAnswer(new Answer() {
 public Object answer(InvocationOnMock invocation) {
     Object[] args = invocation.getArguments();
     Object mock = invocation.getMock();
     return document(fakeIndex((int)(Integer)args[0]));
     }
 });

Argument Captors를 확인합니다.

https://site.mockito.org/javadoc/current/org/mockito/ArgumentCaptor.html

ArgumentCaptor<Integer> argument = ArgumentCaptor.forClass(Integer.class);
Mockito.when(reader.document(argument.capture())).thenAnswer(
  new Answer() {
    Object answer(InvocationOnMock invocation) {
      return document(argument.getValue());
    }
  });

verify()를 ArgumentCaptor 및 ArgumentCaptor와 조합하여 테스트 실행을 확인하고 ArgumentCaptor를 사용하여 인수를 평가할 수 있습니다.

ArgumentCaptor<Document> argument = ArgumentCaptor.forClass(Document.class);
verify(reader).document(argument.capture());
assertEquals(*expected value here*, argument.getValue());

인수 값은 argument.getValue()를 통해 추가 조작/체크 또는 원하는 작업을 수행할 수 있습니다.

Java 8에서는 다음과 같은 경우가 있습니다.

Mockito.when(reader.document(anyInt())).thenAnswer(
  (InvocationOnMock invocation) -> document(invocation.getArguments()[0]));

라고 추측하고 있다document지도입니다.

언급URL : https://stackoverflow.com/questions/6631764/mockito-callbacks-and-getting-argument-values

반응형