Mockito when and thenReturn语句不适用于Java中的2个方法调用

问题描述

在我的Test类中,我有以下模拟语句:

when(Metadata.getGranularity(message)).thenReturn(new Assembly.Partition.Builder.build());

基本上,我通过两种不同的测试方法调用上述声明。第一个是现有的并且可以正常工作,第二个是我的新编写的代码,它调用相同的方法。在设置方法中有提及。在两种情况下都会执行它,当我评估值时,在两种情况下都会提供对象引用,如下所示:

result= {Assembly$Partition@3793}

我班上正在嘲笑的代码是:

Assembly.Partition granularity = Metadata.getGranularity(message);

但是,当调试器从测试方法转到代码时,构建器在第一种情况下创建对象引用,即granularity= {Assembly$Partition@3892},但在第二种情况下,它将引用赋予空值。

此外,有时在调试时,它会给我这个调试错误,即toString()无法返回分区。

编辑

现有的测试方法是:-

public void publish()
filePublisher.publishFirst(message,event,name);
verify(file publisher,times (1)).publishFile(anyString(),anyList(Mylist.class));

我的新方法是:-

public void publish2()
filePublisher.publishSecond(date,id,type);
verify(file publisher,anyList(Mylist.class));

这两种方法都会计算各种数据以调用 publishFile 方法

解决方法

您确实还没有添加足够的(实际)代码来确定这一点,所以不要指望真正的答案!这是一个猜测:

when(metadata.getGranularity(message))... 

...仅在确切的message到达时进行嘲笑。 publish2示例是

filePublisher.publishSecond(date,id,type);

其中date != message

尝试一下:

when(metadata.getGranularity(any())).thenReturn(new Assembly.Partition.Builder.build());