java – 模拟方法返回null

我有以下方法

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

为此我写了以下junit测试代码

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

在测试方法时

该声明

Table table = getTableInstance("Sampletable");

运行正常,并提供模拟表对象但声明

table.getScanner(scan);

返回null.

请在以下链接中找到Table界面的源代码

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

请指导我这个?

最佳答案 用.替换最后一行测试用例

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

它应该工作

点赞