Mockito @Spy 和 @Mock 之间的区别(answer = Answers.CALLS_REAL_METHODS) [英] Difference between Mockito @Spy and @Mock(answer = Answers.CALLS_REAL_METHODS)

查看:28
本文介绍了Mockito @Spy 和 @Mock 之间的区别(answer = Answers.CALLS_REAL_METHODS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mockito 中这两个声明有什么区别?

What is the difference between these two declarations in Mockito?

@Mock(answer = Answers.CALLS_REAL_METHODS)
ArrayList<String> mock;

@Spy
ArrayList<String> spy;

推荐答案

之前的CALLS_REAL_METHODS 样式创建了一个未初始化的对象;没有构造函数运行,也没有设置字段.通常这种语法是不安全的,因为实际的实现会与可能构成无效或不可能状态的未初始化字段交互.

The former CALLS_REAL_METHODS style creates an uninitialized object; no constructors are run and no fields are set. Generally this syntax is unsafe, as real implementations will interact with uninitialized fields that may constitute an invalid or impossible state.

后一种@Spy 风格允许您调用您选择的构造函数,或者 Mockito 将 如果字段未初始化,请尝试调用无参数构造函数.然后将这些字段复制到生成的 Spy(扩展了 spy-on 类型)中,从而实现更安全、更真实的交互.

The latter @Spy style allows you to call a constructor of your choice, or Mockito will try to call a no-arg constructor if the field is uninitialized. The fields are then copied into a generated Spy (that extends the spied-on type), allowing for much safer and more-realistic interactions.

必要提醒:不要在玩具示例之外实际模拟 Java 集合,并且不要忘记在覆盖间谍和 CALLS_REAL_METHOD 模拟时使用 doReturn 语法,否则您将在其中调用真实方法when 调用.

Requisite reminder: Don't actually mock Java collections outside of toy examples, and don't forget to use doReturn syntax when overriding spies and CALLS_REAL_METHOD mocks or else you'll call the real method within the when call.

这篇关于Mockito @Spy 和 @Mock 之间的区别(answer = Answers.CALLS_REAL_METHODS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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