1

I have a test calling a transactional method on a separate thread like so:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context.xml")
public class Test {

    @Autowired
    DatabaseBatchService databaseBatchService;

    @Test
    @Transactional
    public void testConcurrentSaves() {
        Entity e = Entity.createNew();

        databaseBatchService.insert(e);

        // Check database for inserted entities
    }
}

@Component
class DatabaseBatchService implements Runnable {

    @PostConstruct
    public void init() {
        Executors.newSingleThreadScheculedExecutor()
                .scheduleAtFixedRate(this, 0, 100, TimeUnit.MILLISECONDS);
    }

    public synchronized void submit(Entity e) {
        // cache entity
    }

    @Transactional
    private synchronized void save() {
        // insert cached entities
    }

    @Override
    public void run() {
        this.save();
    }
}

As the entity is inserted, using logging I can see it appearing in the database. However when I check the state of the database at the end of the test method, the database is empty.

I understand that this is due to the transaction for the thread being rolled back.

From the test, how can I commit these transactions so that the inserted data is available for the test method to see?

George
  • 903
  • 4
  • 19
  • Please check if this helps, try with @Rollback(false) http://stackoverflow.com/questions/9817388/junit-tests-always-rollback-the-transactions – Sripriya V Mar 09 '17 at 11:29

0 Answers0