How to perform TDD using Hibernate

4

I would like to know how to do TDD using Hibernate . I was informed that this ORM stores memory before writing to the possible, so I wanted to know how to test a data that is in memory. For example: do I execute the save command and test to see if this data is saved, is it possible?

    
asked by anonymous 19.02.2014 / 23:33

3 answers

4

You have to understand the following, the cache is linked to the PersistenceContext that is created when you create an EntityManager.

You can seamlessly use JUnit with EntityManager to test your DAO. What you should do is:

  • Add HSQLDB as a dependency or some other bank in memory
  • To have a persistence.xml just for the test, in that case, it would be enough to add it inside a test directory, in the case of maven, that this context switch would be automatically made.
  • Create a static EntityManagerFactory:

    private static EntityManagerFactory entityManagerFactory;

  • Create a static method annotated with @BeforeClass that will create the EntityManagerFactory:

    @BeforeClass public static void createPersistenceUnit () {     entityManagerFactory = Persistence.createEntityManagerFactory ("PU") }

  • Create a static method annotated with @AfterClass to kill the EntityManagerFactory:

    @AfterClass public static void closePersistenceUnit () {     entityManagerFactory.close (); }

  • Create a method annotated with @Before to start the EntityManager with each test:

    @Before public void beforeTest () {     entityManager = getEntityManagerFactory (). createEntityManager (); }

  • Create a method with @After to end the EntityManager after each test:

    @After public void finishTest () {     entityManager.close (); }

  • This way you will have an EntityManager for each test and your first level cache will be no problem.

    This post is a bit old, but talk about it: link

        
    20.02.2014 / 14:45
    4

    You can not use only the first-level Hibernate cache for use in test cases. The best approach to this problem is to configure Hibernate to use some in-memory database.

    Some in-memory databases that you can use are: HSQLDB, Apache Derby, or H2DB.

    Just create a DataSource for any of these BDs and use it in the Hibernate configuration used in your test cases.

    Example: link

        
    20.02.2014 / 06:31
    1

    I think you're going down the road to test technology, not the business domain of your problem.

    I think you could try to "mock" hibernate with a mockito for example and not worry so much about technology but with business rules, that's why we use TDD ... :-)

        
    20.02.2014 / 13:08