在Kotlin中打开getter以将其与Mockito - MissingMethodInvocationException一起使用

问题描述 投票:2回答:4

Kotlin可以自动为主构造函数参数创建getter(这很棒),默认情况下所有这些getter都是final(非打开)。我有一节课(在Kotlin):

open class SongCategory(val id: Long,
                        val type: SongCategoryType,
                        val name: String? = null,
                        var displayName: String? = null,
                        var songs: List<Song>? = null) {
}

我想在一些Mockito测试中使用它(在Java中):

SongCategory songCategory = mock(SongCategory.class);
// the line below produces MissingMethodInvocationException
when(songCategory.getDisplayName()).thenReturn("Dupa");

这会产生MissingMethodInvocationException,因为Mockito需要被模拟的类是开放的(而不是最终的)而模拟的方法getDisplayName()只需要打开但不是。

我不能打开这个getter或创建另一个重写的getter,因为它与为构造函数自动创建的最终getter冲突。

我可以将所有参数移动到辅助构造函数,并分别创建所有属性和getter。但是,如果我必须编写与Java相同的样板代码,那么使用Kotlin的意义何在呢?

有没有办法将Mockito与Kotlin编译的getter一起使用?

java kotlin mockito getter
4个回答
3
投票

open你的班级只是为了测试。而是尝试使用编译器插件为您执行此操作。你可以在这里阅读:https://kotlinlang.org/docs/reference/compiler-plugins.html#all-open-compiler-plugin

完成后,您将能够像其他任何Java类一样使用Mockito。


1
投票

您可以尝试使用PowerMock来处理最终方法

或者Javasist及其javassist.Modifier


1
投票

我同意@Unknown,有些地方你可以使用kotlin-allopen插件。但在这种情况下,因为你要做的就是模拟一个Kotlin类(那个没有打开),你只需要添加mockito-inline插件。

将以下内容添加到您的build.gradle

testImplementation 'org.mockito:mockito-core:2.13.0' // use the latest version
testImplementation 'org.mockito:mockito-inline:2.13.0'

0
投票

实际上,我发现打开一个getter的语法非常简单(尽管它不在官方文档中):

open class SongCategory(...
                        open var displayName: String? = null,
                        ...) {
}

这将打开属性的getter和setter。

© www.soinside.com 2019 - 2024. All rights reserved.