Mocking a method returns null

折月煮酒 提交于 2019-12-10 17:21:35

问题


I have the following method

public ResultScanner getScanner(Scan scan) {
    Table table = getTableInstance("Sampletable");
    return table.getScanner(scan);
}

For this I have written following junit test code

Connection mockconnection = PowerMockito.mock(Connection.class);
Table mocktable = PowerMockito.mock(Table.class);
PowerMockito.when(mockconnection.getTable(TableName.valueOf(Mockito.anyString())))
    .thenReturn(mocktable);

Scan mockedScan = PowerMockito.mock(Scan.class);
ResultScanner mockrs = PowerMockito.mock(ResultScanner.class);
PowerMockito.when(mocktable.getScanner(mockedScan)).thenReturn(mockrs);

while testing the method

the statement

Table table = getTableInstance("Sampletable");

runs fine and gives the mocked table object but the statement

table.getScanner(scan);

returns null.

Please find the source code for Table interface in the below link

http://grepcode.com/file/repo1.maven.org/maven2/org.apache.hbase/hbase-client/1.1.1/org/apache/hadoop/hbase/client/Table.java

Please guide me in this??


回答1:


Replace last line of test case with

 PowerMockito.when(mocktable.getScanner(Mockito.any(Scan.class))).thenReturn(mockrs);

It should work



来源:https://stackoverflow.com/questions/41165788/mocking-a-method-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!