unit-testing - Mockito.thenReturn(...) 不工作

标签 unit-testing testing junit mocking mockito

测试类

public class CollectionImplementationUnitTest {

  CollectionImplementation colImp;

  public void setup() throws Exception {
    ...
    colImp = Mockito.spy(new CollectionImplementation());
    ...
  }

  private String mockHistoryFromStrgyTable() {
    String value1 = "myValue";
    return value1;
  }

  @Test 
  public void testgetinfo (){
    ...
    Mockito.when(
      colImp.historyFromStrgyTable(
         Mockito.anyString(),Mockito.anyString(),Mockito.anyString()
      )
    )
    .thenReturn(mockHistoryFromStrgyTable());

    CollectionsAccount Info = colImp.accountInfo(
      "string1","string2","string3", new IdentityAcc(), TableLst
    );

    //sometestmethods and asserts
  }
}

被测类

public class CollectionImplementation {
  ...
  @Override
  public CollectionsAccount accountInfo(("string1","string2","string3", new IdentityAcc(), TableLst)) {
      DetailsHelper helper = new (db2, "string",getmethod());
      return helper.accountInfo("string1","string2", new IdentityAcc(), TableLst); 
  }

  public String historyFromStrgyTable(){
    //contains a call to the data base
  }
}

DetailsHelper

public class DetailsHelper{
  public CollectionsAccount accountInfo((String string1,String string2,String string3, new IdentityAcc(), TableLst)){
  ...
  String paymentdetails = historyFromStrgyTable();  
  }
   public String historyFromStrgyTable(){
   //contains a call to the data base
   }
}

当我尝试模拟 HistoryFromStrgyTable() 方法的数据时,它实际上是在调用 HistoryFromStrgyTable() 而不是从 mockHistoryFromStrgyTable() 获取数据。

我的测试用例在这一行失败了

Mockito.when(col_Imp.HistoryFromStrgyTable(Mockito.anyString(),
  Mockito.anyString(),Mockito.anyString())).thenReturn(  mockHistoryFromStrgyTable());

谁能帮我解决这个问题。我不明白怎么了。我还将 mockHistoryFromStrgyTable() 方法从私有(private)更改为公共(public),因为 mockito 无法模拟私有(private)方法。

最佳答案

发生这种情况是因为您使用的是 spy ,而不是模拟。当您调用它时运行“真正的”方法正是 Mockito spy 应该做的。

要 stub 您的 spy ,这是您要使用的语法。

Mockito.doReturn(mockHistoryFromStrgyTable()).when(colImp).
    historyFromStrgyTable(Mockito.anyString(),Mockito.anyString(),Mockito.anyString());

您可以在 my post here 中找到更多详细信息.

关于unit-testing - Mockito.thenReturn(...) 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38677048/

相关文章:

sql - 为什么这个 Groovy MetaClass 语句可以与 Sql 类一起使用?

C# 单元测试复杂处理程序网络

ruby-on-rails - 如何仅在 Rails 的测试环境中插入日志?

spring - 在服务中模拟服务 (JUnit)

sql-server - 在单元测试之前运行脚本

c# - 什么是功能测试?

ios - 单元测试,iOS,DTXProxyChannel 错误 1

java - 如何测试在类路径上找不到文件? java( Spring @Configuration)

java - 如何在两个不同的数据库上运行 JUnit 测试

java - 如何编写多线程单元测试?