Lawik
05/01/2019, 8:10 AMMockk
I am trying to mock the following function fun <T> openAndCloseSession(handler: (Session) -> T): T {
val session = HibernateUtil.sessionFactory.openSession()
val res = handler(session)
if (session.isOpen) {
session.close()
} else {
println("[WARNING]: session closed by handler function: ${handler::class.java.enclosingMethod}, please consider omitting manually closing the session in the handler as it will be closed automatically at the end of the call")
}
return res
}
I want the mock to just call the provided handler
(which I have mocked too). This is where I am currently at val session: Session = mockk()
every { openAndCloseSession<Any>(any()) } answers {firstArg<(Session) -> Any>().invoke(session)}
Sadly this doesn't work.tddmonkey
05/01/2019, 10:01 AMhandler
or this entire function?Lawik
05/01/2019, 11:23 AMmockkStatic(..)
.Lawik
05/01/2019, 11:28 AMtddmonkey
05/01/2019, 11:59 AMLawik
05/01/2019, 12:22 PMopenAndCloseSession
to create a new Hibernate session which will remain open within the handler in which an action is performed (usually a DAO function) and returns the results of the handler. I just want to test my endpoint, I mocked the (DAO) functions that my endpoints call, I wanted to skip the creation of the Hibernate session and the mocked function to just call the handler immediately as the handler is mocked anyway. I hope it makes sense 😅tddmonkey
05/01/2019, 1:29 PMLawik
05/01/2019, 1:35 PMtddmonkey
05/01/2019, 2:11 PMtddmonkey
05/01/2019, 2:11 PMLawik
05/01/2019, 2:29 PM@Path(PersonPaths.ROOT)
@Produces(MediaType.APPLICATION_JSON)
actual class PersonEndpoint : Endpoint() {
@GET
@Path(PersonPaths.GET_BY_ID)
actual suspend fun getById(@PathParam("id") id: Long): PersonDTO = openAndCloseSession {
val genericDaoImpl = GenericDaoImpl<Person, Long>(Person::class.java, it)
genericDaoImpl.load(id)
}?.dto ?: throw WebApplicationException(Response.Status.NOT_FOUND)
@GET
actual suspend fun getAll(): List<PersonDTO> = openAndCloseSession {
val genericDaoImpl = GenericDaoImpl<Person, Long>(Person::class.java, it)
genericDaoImpl.loadAll()
}.map { it.dto }
@GET
@Path(PersonPaths.RESULTS_LIST_PATH)
actual suspend fun getAllResultsList(): ResultsList<PersonDTO> = ResultsList(openAndCloseSession {
val genericDaoImpl = GenericDaoImpl<Person, Long>(Person::class.java, it)
genericDaoImpl.loadAll()
}.map { it.dto })
@POST
@Status(201)
actual suspend fun create(personDTO: PersonDTO): Long = openAndCloseSession {
val genericDaoImpl = GenericDaoImpl<Person, Long>(Person::class.java, it)
genericDaoImpl.save(personDTO.entity)
}
}