使用mockito使用模拟对象断言一个对象

时间:2018-03-12 10:04:33

标签: java junit mockito

我正在尝试使用模拟对象测试elasticsearch客户端对象的创建。

界面如下所示

public interface DBClient<T> {
    public T getClient() throws Exception;
}

实现如下所示

public class ElasticSearchClient implements DBClient<RestClient> {

    private String _hostName, _scheme;
    private int _port;

    public ElasticSearchClient(String hostname, int port, String scheme) {
        this._hostName = hostname;
        this._port = port;
        this._scheme = scheme;
    }

    public RestClient getClient() throws Exception {

        return RestClient.builder(new HttpHost(_hostName, _port, _scheme)).build();

    }
}

我正在编写测试用例以检查我是否获得了有效对象

@RunWith(MockitoJUnitRunner.class)
public class DBClientTest {

    private final String hostname = "search-sdsessec-us-east-2.es.amazonaws.com";
    private final int port = 443;
    private final String scheme = "https";

    @Mock
    public DBClient<RestClient> dbClientMock;

    @Test
    public void testGetClientReturnsElasticSearchClient() throws Exception {
        ElasticSearchClient esClient = new ElasticSearchClient(hostname, port, scheme);
        Assert.assertEquals(esClient.getClient(), when(dbClientMock.getClient()).thenReturn(RestClient.builder(new HttpHost(hostname, port, scheme)).build()));
    }

}

这是正确的测试方式吗?请帮忙。

0 个答案:

没有答案