Esperanz0
Esperanz0

Reputation: 1586

Use Kotlin annotation class in Java class

I'm writing new features in Kotlin but some stuff are already wrote in Java.

I'm writing tests in Mockito(Kotlin) but Mockito has problem with final class so I created:

annotation class Mockable {}

And added to Gradle-build:

apply plugin: 'kotlin-allopen'

allOpen {
    annotation('com.Mockable')
}

So using this annotation class I can mock Kotlin class.

How I can use this annotation in Java class ?

Upvotes: 0

Views: 474

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170745

How I can use this annotation in Java class ?

You can't use this annotation in this way, because kotlin-allopen only works on Kotlin classes. In Java, just don't mark classes as final...

For that matter, in Kotlin it doesn't seem useful either if I understood you correctly: kotlin-allopen is used when the annotation is going to be processed in some way which requires creating subclasses of the annotated type, so you'd need to write open as well as annotation. Here, you can write open instead of @Mockable.

Upvotes: 1

tynn
tynn

Reputation: 39843

You don't need it in Java. But regardless of this, there's an alternative method to use Mockito with Kotlin:

Create a file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker with contents:

mock-maker-inline

This changes the mocking behavior to also support final classes like the Kotlin ones. For some Java classes I had to use spy() instead of mock() afterward though.

Upvotes: 1

Related Questions