首页 > Java > java教程 > Mockito:'doReturn()”与'when()”:什么时候应该对间谍对象使用which?

Mockito:'doReturn()”与'when()”:什么时候应该对间谍对象使用which?

Patricia Arquette
发布: 2024-11-28 18:19:15
原创
1131 人浏览过

Mockito: `doReturn()` vs. `when()`: When Should You Use Which with Spied Objects?

Mockito:理解 doReturn() 和 when() 之间的细微差别

使用模拟框架 Mockito 增强测试能力时,开发人员经常会遇到 doReturn()和when() 方法。虽然这两种方法都用于存根方法调用,但在处理间谍对象(用 @Spy 注释)时,它们之间存在细微的区别。

when(...).thenReturn(...) 与doReturn(...).when(...)

when(...).thenReturn(...):

  • 创建一个返回指定值之前真正的方法调用。
  • 如果被调用的方法抛出异常,则必须对其进行处理或模拟

doReturn(...).when(...):

  • 完全避免实际的方法调用。

实际示例

考虑以下内容MyClass:

1

2

3

4

5

6

7

8

9

public class MyClass {

    protected String methodToBeTested() {

        return anotherMethodInClass();

    }

 

    protected String anotherMethodInClass() {

        throw new NullPointerException();

    }

}

登录后复制

测试间谍

doReturn(...).when(...):

1

2

3

4

5

@Spy

private MyClass myClass;

 

// Works as expected

doReturn("test").when(myClass).anotherMethodInClass();

登录后复制

when(...).thenReturn(.. .):

1

2

// Throws a NullPointerException

when(myClass.anotherMethodInClass()).thenReturn("test");

登录后复制

在这种情况下,doReturn() 确保异常避免了 anotherMethodInClass(),同时仍然返回所需的值。相比之下,when() 会触发实际的方法调用,导致抛出 NullPointerException。

因此,在处理间谍对象时,选择 doReturn() 和 when() 取决于您是否要调用实际方法或完全绕过它。

以上是Mockito:'doReturn()”与'when()”:什么时候应该对间谍对象使用which?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板