gpt4 book ai didi

kotlin - 模拟 : Mock more than one interface at the same time

转载 作者:行者123 更新时间:2023-12-02 16:37:23 25 4
gpt4 key购买 nike

我正在尝试使用 Mockk 模拟一些接口(interface)。

有时,我必须创建一个实现 2 个接口(interface)的模拟。

例如,在 C# 中使用 Moq,我可以做到 that :

// implementing multiple interfaces in mock
var foo = new Mock<IFoo>();
var disposableFoo = foo.As<IDisposable>();
// now IFoo mock also implements IDisposable :)
disposableFoo.Setup(df => df.Dispose());

有没有办法用 Mockk 做到这一点?

如果我尝试类似的东西

val foo : IFoo = mockk()
every { (foo as AutoCloseable).close() } just Runs

我收到以下错误(这是有道理的):

com.example.IFoo$Subclass0 cannot be cast to java.lang.AutoCloseable

我在文档中看到我可以使用 spyk 指定额外的接口(interface),但我不想在这里使用实际的实现。

有办法吗?还有其他方法吗?

最佳答案

可以通过 moreInterfaces 参数实现。

spyk 文档中的示例。也应该与 mockk 一起工作:

val spy = spyk(System.out, moreInterfaces = *arrayOf(Runnable::class))

关于kotlin - 模拟 : Mock more than one interface at the same time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62412920/

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