我试图模拟以下模式的超载方法
JestClient {
DocumentResult execute(Index x) {...}
BulkResult execute(Bulk y ) {...}
}
我使用以下代码创建模拟。
JestClient client = Mockito.mock(JestClient.class);
DocumentResult setResult = Mockito.mock(DocumentResult.class);
when(setResult.isSucceeded()).thenReturn(true);
BulkResult bulkResult = Mockito.mock(BulkResult.class);
when(bulkResult.isSucceeded()).thenReturn(true);
// when(client.execute(Mockito.any(Index.class))).thenReturn(setResult);
// when(client.execute(Mockito.any(Bulk.class))).thenReturn(bulkResult);
doReturn(setResult).when(client).execute(Mockito.any(Index.class));
doReturn(bulkResult).when(client).execute(Mockito.any(Bulk.class));
JestClientFactory factory = Mockito.mock(JestClientFactory.class);
when(factory.getObject()).thenReturn(client);
最终的模拟总是返回第二个模拟,而忽略了第一个模拟,而不管传递的对象类型以参数为单位。
我希望我使用答案是可以的,因为它不适合评论。您是否尝试在这里使用Mockito.argThat(Hamcrest.isA(SomeClass.class))
?
doReturn(setResult).when(client).execute(argThat(isA(Index.class)));
如果您提供可执行的示例,这将很有帮助。我试图重新实现您的情况,但我的测试是绿色的。您的情况有什么不同?
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.isA;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import org.junit.Test;
public class SomeTest {
@Test
public void testName() throws Exception {
JestClient client = mock(JestClient.class);
DocumentResult setResult = mock(DocumentResult.class);
BulkResult bulkResult = mock(BulkResult.class);
doReturn(setResult).when(client).execute(any(Index.class));
doReturn(setResult).when(client).execute(argThat(isA(Index.class)));
doReturn(bulkResult).when(client).execute(any(Bulk.class));
assertThat(client.execute(new Index()), isA(DocumentResult.class));
assertThat(client.execute(new Bulk()), isA(BulkResult.class));
}
public class Input {}
public class Index extends Input {}
public class Bulk extends Input {}
public class JestClient {
DocumentResult execute(Index x) {
return new DocumentResult();
}
BulkResult execute(Bulk y) {
return new BulkResult();
}
}
public class BulkResult {}
public class DocumentResult {}
}