模拟方法返回null

时间:2016-12-15 13:49:14

标签: java unit-testing mockito powermock

我有以下方法

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

请指导我吗?

1 个答案:

答案 0 :(得分:1)

替换测试用例的最后一行
 PowerMockito.when(mocktable.getScanner(Mockito.any(Scan.class))).thenReturn(mockrs);

应该有效