Mock Entity Manager

206 views
Skip to first unread message

Suren Hiraman

unread,
Feb 27, 2014, 3:26:58 PM2/27/14
to play-fr...@googlegroups.com

I have some (Scala) code in Play which uses JPA for DB access. Works fine. But I want to unit test my code, which will require using a mock EntityManager. Is this possible?

My test is written in specs2 (by extending PlaySpecification) and is run with JUnit. I am using Mockito to mock the EntityManager. But I would expect to be able to do this with other frameworks.

Here's what my code looks like:

object MyThing {
    def create(...) : MyThing = {
        val newThing = ...
        JPA.withTransaction(new play.libs.F.Function0[Unit]() {
            def apply() = {
                JPA.em().persist(newThing)
            }
        })
        return newThing
    }
}

If it is not possible to unit test this code, is there some alternate approach to data access which is recommended?

Will Sargent

unread,
Feb 27, 2014, 3:37:04 PM2/27/14
to play-fr...@googlegroups.com
So this is what I do, and what I think is a best practice: I create a database persistence subproject in SBT (i.e. like http://beauhinks.com/play2-multi-swagger-metrics-tutorial/), define some data services with interfaces available to Play, and then do all the JPA work inside that subproject.  

Then, you can mock out access to your interfaces without having to touch JPA directly, and you can isolate your persistence from your HTTP work (i.e. your Play project can contain only DTOs and not have to deal with transactions, etc).

Will Sargent
Consultant, Professional Services
Typesafe, the company behind Play Framework, Akka and Scala


--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to play-framewor...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Suren Hiraman

unread,
Feb 27, 2014, 3:41:04 PM2/27/14
to play-fr...@googlegroups.com
Thanks, Will. That's the conclusion we are coming to as well.

We had some existing code already but it's probably the right thing to do to create that DAL/service layer that can be mocked.

-Suren

Alberto Souza

unread,
Feb 27, 2014, 9:13:32 PM2/27/14
to play-fr...@googlegroups.com
I think that mock EntityManager is dangerous... There is no need to unit test MyThing... It should interact with Database to test your queries... So you can run a integration test and check the behavior.

Cheers,

Reply all
Reply to author
Forward
0 new messages