Home > Software design >  Kotlin - Spring - How to pass an interface with generics as an argument to Mockito.any()
Kotlin - Spring - How to pass an interface with generics as an argument to Mockito.any()

Time:10-24

In Kotlin I'm using Mockito to perform unit tests in the when method I'm trying to test my repository which extends JpaRepository which also extends QueryByExempleExecutor and from this interface I want the method findAll(Example<S> example, Pageable pageable) which receives as its first argument the Example interface that has a generics

In Kotlin the method should work like this `when`(repository.findAll(Mockito.any(Example<Book>::class.java), Mockito.any(PageRequest::class.java))).thenReturn(page)

however it doesn't work and the only message I have is this "Only classes are allowed on the left hand side of a class literal"

how can I use the when method passing an interface to Mockito.any() ???

CodePudding user response:

You can create an extension on mockito like this:

inline fun <reified T: Any> any() = Mockito.any(T::class.java)

And then you can use it like this:

`when`(
    repository.findAll(
        example = Mockito.any<Example<Book>>(),
        pageable = Mockito.any<PageRequest>(),
    )
).thenReturn(page)
  • Related