Mockito模拟重载方法

时间:2016-11-30 08:57:01

标签: java unit-testing mockito

我正在尝试模拟以下架构的重载方法

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);

结果模拟总是返回第二个模拟并忽略第一个模拟而不管作为参数传递的对象类型。

1 个答案:

答案 0 :(得分:0)

我希望如果我使用答案就可以,因为它不适合评论。 您是否尝试在此使用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 {}
}