mardi 6 octobre 2020

Mockk: How to mock object id being generated when object is saved

In my test I need to mock a situation, when new object is saved into database using entity manager (em) and during that process, id property of that object is set to auto-incremented id of that row in database. I would like to set that id property to my own value that I could match later in the test.

I'm using mockk 1.9.3 and kotlin 1.4.0.

So far I have this:

val myVal = 123

every { 
     em.persist(any<MyObj>()) 
} answers {
     firstArg<MyObj>().id = myVal
     // return of the persist method
     em
}

But when I try to run that code, I get:

java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class MyObj

Looks like the problem is in the firstArg call. If I place a breakpoint on that line, it will reach it and stop there, the exception occurs when I try to evaluate firstArg<MyObj>().

In documentation I was able to find only example using simple Int. Any ideas why the ClassCastException is thrown?

Aucun commentaire:

Enregistrer un commentaire