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

查看:571
本文介绍了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将

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天全站免登陆