3

I'm trying to unit (integration) test a method annotated with Spring's @Async. The test sets up some data in in-memory h2 database, then runs the asynchronous method. Asynchronous code does not see test data :O Removing @Async fixes the problem.

Any help? :)

macko
  • 244
  • 3
  • 8

2 Answers2

2

I had the same error. The solution was quite simple for me: I did not put a COMMIT; to the end of my data_init-h2.sql

I presume you did not put this either. If you think about it this is quite logical. Your main thread fires up a transaction but does not actually commit it to h2. Spring fires up another thread and the @Async method is run there in a separate transaction.

Because of the lack of commit you do not see the data changes on this other thread. On the main thread you can see your data changes even before they are committed as you are in that transaction.

VSZM
  • 1,341
  • 2
  • 17
  • 31
0

The transaction isn't propagated like it was before your @Async.

@Async and @Transactional: not working

Your test could commit the data and delete it either side of the test, removing Spring's automated rollback inside test @Transactionals.

You could create a default-access method that the async method calls into, that your test could also call direct, though you would no longer be testing the Async behaviour.

There's likely a nicer spring implementation that supports what you need, making the transaction available but I don't have it.

paprika
  • 617
  • 6
  • 12