gpt4 book ai didi

java - 是否需要为 Mockito.mock() 创建一个接口(interface)或实现类?

转载 作者:行者123 更新时间:2023-12-01 09:48:08 28 4
gpt4 key购买 nike

我阅读了教程,但不明白 - 应该实现多少模拟对象。我们是否将一个接口(interface)或整个实现的类传递给mock()?

如果没有实现怎么办?您是否需要创建一个接口(interface) - 假设您由于不了解实际实现而省略了一些方法...

来自mockito.org 的示例 here

//mock creation
List mockedList = mock(List.class);

我需要使用 android List 类的方法创建一个“List”类吗?

最佳答案

Mockito 每个方法的默认实现由 RETURNS_DEFAULTS 给出,(除非另有配置)遵循 ReturnsEmptyValues :

Default answer of every Mockito mock.

  • Returns appropriate primitive for primitive-returning methods
  • Returns consistent values for primitive wrapper classes (e.g. int-returning method returns 0 and Integer-returning method returns 0, too)
  • Returns empty collection for collection-returning methods (works for most commonly used collection types)
  • Returns description of mock for toString() method
  • Returns zero if references are equals otherwise non-zero for Comparable#compareTo(T other) method (see issue 184)
  • Returns an java.util.Optional#empty() empty Optional for Optional (see issue 191).
  • Returns null for everything else

对于传递给 Mockito.mock() 的类上任何可模拟但未 stub 的方法,模拟方法默认情况下都会具有此行为,无论您是否传入具体的类或接口(interface)。事实上,Mockito 鼓励您仅 stub 对被测系统有值(value)的方法,并让默认值适用于其他所有内容。如果您“忘记” stub 方法,或者在编写测试后添加新方法,也会出现这种情况。

请注意,对于 Mockito.spy,默认行为是委托(delegate)给您传递给 spy 的实例(副本),并且通过将其他参数传递给Mockito.mock 如果您愿意,您可以更改此“默认答案”。

关于java - 是否需要为 Mockito.mock() 创建一个接口(interface)或实现类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37818904/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com