gpt4 book ai didi

java - 如何在 Mockito 中模拟 instanceof

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:33 24 4
gpt4 key购买 nike

我有一段代码,我想用 Mockito 测试:

mockedClass instanceof SampleInterface

mockedClass 是模拟抽象类:MockedClassSampleInterface 是一个接口(interface)。这是失败点:

Validate.isTrue(mockedClass instanceof SampleInterface, "The mockedClass is not a SampleInterface");

如何模拟这段代码?

最佳答案

听起来你需要MockSettings.extraInterfaces .

MockedClass mockedClass = mock(MockedClass.class,
withSettings().extraInterfaces(SampleInterface.class));

请注意,它带有自己的警告标签:

This mysterious feature should be used very occasionally. The object under test should know exactly its collaborators & dependencies. If you happen to use it often than [sic] please make sure you are really producing simple, clean & readable code.

作为替代方案,创建一个用于测试的接口(interface),它扩展了您希望模拟实现的所有接口(interface),并以通常的方式对其进行模拟。

public abstract class ForTest implements SampleInterface {}

MockedClass mockedClass = mock(ForTest.class);

关于java - 如何在 Mockito 中模拟 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27602598/

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