模拟方法返回null [英] Mocking a method returns null

查看:101
本文介绍了模拟方法返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法

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

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

 连接模拟连接= PowerMockito.mock(Connection.class); 
表模拟表= PowerMockito.mock(Table.class);
PowerMockito.when(mockconnection.getTable(TableName.valueOf(Mockito.anyString())))
.thenReturn(mocktable);

扫描mockedScan = PowerMockito.mock(Scan.class);
ResultScanner模拟者= PowerMockito.mock(ResultScanner.class);
PowerMockito.when(mocktable.getScanner(mockedScan))。thenReturn(mockrs);

在测试方法时



语句

  Table table = getTableInstance( Sampletable); 

运行良好并给出了模拟表对象,但语句

  table.getScanner(scan); 

返回空值。



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



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



请引导我

解决方案



<$ p代替测试用例的最后一行$ p> PowerMockito.when(mocktable.getScanner(Mockito.any(Scan.class)))。thenReturn(mockrs);

应该可以工作


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??

解决方案

Replace last line of test case with

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

It should work

这篇关于模拟方法返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆