Home > Software design >  Unit Test kotlin for hibernate.sessionfactory.createQuery using mockk, what does this mean?
Unit Test kotlin for hibernate.sessionfactory.createQuery using mockk, what does this mean?

Time:06-28

I'm trying to mock out my calls to hibernate using the mockk framework. I need to mock the Query object that is returned by here. When I use the following code I get this compiler error, which not being a kotlin developer I don't understand.

Type mismatch: inferred type is () -> Query but Query<(raw) Any!>! was expected

        var mockedQuery = mockk<Query<Any>>{ }
        var mockSessionFactory = mockk<SessionFactory> {
        every { openSession() } returns mockk {
            every { get(any(), any()) } returns { null }
            every { createQuery("delete from SaveableObject where expiration < getdate() ") } returns { mockedQuery }
        }
    

How do I mock out that Query object?

CodePudding user response:

    var mockedQuery = mockk<Query<Any>>()
    var mockSessionFactory = mockk<SessionFactory> {
        every { openSession() } returns mockk {
            every { get(any(), any()) } returns null
            every { createQuery("delete from SaveableObject where expiration < getdate() ") } returns mockedQuery
        }
    }

I think the problem here is that you are using Supplier functions instead of the actual value.

A Supplier, as in Java, is a function with a signature () -> T and if you place a value in curly braces, you are assigning a Supplier, not the actual value.

Imagine

var helloWorld = { "Hello World" }

You cannot lowerCase it as helloWorld.lowerCase(), you need to call the function first helloWorld().lowerCase().

In the same way, createQuery wants Query<Any> returned, not () -> Query<Any>

The other thing I changed is that I called mockk() for the query following one of the ways mentioned in the documentation for object mocks which don't get any behavior injected.

  • Related