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

Mockito when and thenReturn statement not working for 2 method calls in Java

在我的测试 class 中,我有以下模拟语句:

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

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

result= {Assembly$Partition@3793}

我的 class 中它正在模拟的代码是:

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

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

此外,有时在调试时,它会给我这个调试错误,即 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, times (1)).publishFile(anyString(), 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());