Mockito.thenReturn(...)无法正常工作 [英] Mockito.thenReturn(...) in not working

查看:864
本文介绍了Mockito.thenReturn(...)无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试类

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()获取.

When I try to mock the data for the method HistoryFromStrgyTable() it is actually making a call to HistoryFromStrgyTable() instead of getting from mockHistoryFromStrgyTable().

我的测试用例在此行失败

My test cases are failing at this line

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

任何人都可以帮我这个忙.我不明白怎么了我还将方法mockHistoryFromStrgyTable()从私有更改为公共,因为模拟无法模拟私有方法.

Can anyone help me with this. I don't understand what's wrong. I also changed the method mockHistoryFromStrgyTable() from private to public since mockito cannot mock private methods.

推荐答案

之所以发生这种情况,是因为您使用的是间谍而不是模拟游戏.调用它时,运行真实"方法正是应该要做的Mockito间谍.

This is happening because you're using a spy, not a mock. Running the "real" method when you call it is exactly what Mockito spies are supposed to do.

要侦探间谍,这是您要使用的语法.

To stub your spy, this is the syntax that you want to use.

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

您可以在我在此处的帖子中找到更多详细信息.

You can find more detail on this in my post here.

这篇关于Mockito.thenReturn(...)无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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