Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring start parallel transactions in integration test

I've been looking around for a solution but can't seem to find a good one. I have a complex scenario in which I would like to evaluate the behavior of hibernate optimistic locking vs pessimistic locking

The perfect place to do this would be in a good set of integration tests, but I can't seem to be able find a clean way of starting parallel transactions.

  • How can I create 2 parallel transactions in a spring integration test without manually creating Threads and injecting SessionFactory objects.

Note that I haven't found a way to create 2 parallel transactions without spawning at least 2 threads (maybe there is a way, I hope you can show me an example of that).

like image 277
victor Avatar asked Feb 19 '16 10:02

victor


People also ask

Does spring run tests in parallel?

- [Instructor] One of the bigger improvements from a testing perspective with Spring 5 is the ability to now execute our tests in parallel. Now, this really is an important consideration, especially if you have a lot of tests. Very large test suites take a lot of time to run.

What annotation is used on an integration test method to run it in a transaction?

@Transaction annotation for integration testing in Spring Boot.

Can JUnit be used for integration testing?

And what are they using it for? Even after 20 years of JUnit's existence it is still mostly being used for unit tests. If you are lucky you may see an integration test or two. JUnit is, in fact, much more than a unit testing framework.


1 Answers

Adding this as an answer as there's not enough space on the comments:

In the past, I've tested on vanilla Spring by creating different EntityManager/Session and later injecting those. I'm not sure how you can do this from an Spring integration test, but it might spark an idea.

In the following code, Account is a tiny object which is versioned. You can achieve the same, if the Spring Integration flow (or whatever is called) can be instantiated with a custom entity manager.

public void shouldThrowOptimisticLockException() {
      EntityManager em1 = emf().createEntityManager();
      EntityManager em2 = emf().createEntityManager();
      EntityTransaction tx1 = em1.getTransaction();
      tx1.begin();

      Account account = new Account();
      account.setName("Jack");
      account.updateAudit("Tim");

      em1.persist(account);
      tx1.commit();


      tx1.begin();
      Account account1 = em1.find(Account.class, 1L);
      account1.setName("Peter");

      EntityTransaction tx2 = em2.getTransaction();
      tx2.begin();
      Account account2 = em2.find(Account.class, 1L);
      account2.setName("Clark");

      tx2.commit();
      em2.close();

      tx1.commit(); //exception is thrown here
      em1.close();
}
like image 167
Augusto Avatar answered Oct 10 '22 23:10

Augusto