1

All my services extend one abstract class DefaultBaseService<T :HasID<ID>, ID> with some basic CRUD methods like:

override suspend fun update(id: ID, obj: T): T {
    obj.id = id
    return save(obj)
}
override suspend fun update(id: ID, map: HashMap<String, Any>): T {
 /* ... */
return update(id, obj)
}

So my Service extends it like this:

@Service
class FooService(val fooRepository: FooRepository): DefaultBaseService<Foo, ObjectId>(fooRepository, Foo::class)

And I have a RabbitMQ listener class FooListener with this service injected, that I'm trying to test with MockK and JUnit.

My test class is like this

@ExtendWith(MockKExtension::class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
class FooListenerTests {

    @MockK
    lateinit var fooService: FooService

    @MockK
    lateinit var barService: BarService

    @InjectMockKs
    lateinit var listener: FooListener

    @BeforeAll
    fun setUp() = MockKAnnotations.init(this, relaxUnitFun = true)

    @Test
    fun `should listen do event`() {
        coEvery { fooService.create(any()) } returns Templates.foo
        coEvery { fooService.save(any()) } returns Templates.foo
        coEvery { fooService.update(any(), any<Foo>()) }
        coEvery { barService.create(any()) } returns Templates.bar

        listener.listenToSomething(Templates.event)
    }
}

And when I run the test I get this error

Jun 27, 2023 12:16:14 PM io.mockk.impl.log.JULLogger warn
WARNING: Failed to transform class com/numih/mongodb/commons/service/DefaultBaseService
java.lang.IllegalArgumentException: Cannot resolve T from static java.lang.Object com.numih.mongodb.commons.service.DefaultBaseService.update$suspendImpl(?)

I already tried using Mockito instead of MockK but keep getting the same error and I've been a while without creating tests in my application due to this error

I also tried replacing any<Foo>() for ofType(Foo::class) but generates the same error

Arthur
  • 11
  • 2

1 Answers1

0

You can just replace the @MockK annotation to @MockBean from Spring Starter Test dependency.

Then the final class should look like this

@ExtendWith(MockKExtension::class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
class FooListenerTests {

    @MockBean
    lateinit var fooService: FooService

    @MockBean
    lateinit var barService: BarService

    @InjectMockKs
    lateinit var listener: FooListener