JUnit Multithreaded Test with Spring Transactions

I am running a JUnit integration test with an in-memory H2 database configured like so:

public DataSource dataSource() {

    try {
        SimpleDriverDataSource simpleDriverDataSource = new SimpleDriverDataSource();
        simpleDriverDataSource.setDriverClass((Class<? extends Driver>) ClassUtils.forName("org.h2.Driver", this.getClass().getClassLoader()));

        return simpleDriverDataSource;
    } catch(ClassNotFoundException e) {
        throw new IllegalStateException(e.getMessage());


The test makes a call to a service method. This service method uses an executor service to fork the processing. Before the call to the service class, the test method inserts some data into the database, and this data can be read using the service (via JPA repository calls) up until the task is submitted to the executor service. However, when the task is run, it is unable to read the data that was persisted previously.

How can I make the forked thread see the persisted data?

Note: This is only failing for the Unit test, it is working fine at runtime.


Assuming that your test is @Transactional, what you see is the expected behaviour as you (usually) don't want the changes made by a test to be visible to other part of the system, and possibly, rolled back at the end of the test.

A simple way to work around this problem is to annotate the @Test method like this

@Transactional(propagation = Propagation.NEVER)
public void testYourLogics() { /* ... */ }

I've been able to reproduce tour behaviour without the propagation = Propagation.NEVER and to see it solved with it.

Please note that you will have to restore the database to a clean state manually after running the test, or the changes made by that test, will be visible to the other tests

Need Your Help

IAd banner moves entire skscene upwards

swift sprite-kit iad

I put an ad banner in my spritekit game and when an ad shows up, the banner shoves the entire screen upwards. I tried changing the zposition of the banner but that did nothing.

Simple reusable javascript averaging function for multiple forms on same page

javascript average

I literally started trying to teach myself javascript less than 48 hours ago. Outside of just wanting to learn it I also have a small personal project I'm working on and using as sort of my working