0
votes

I have some Spring Services which I want to test. These Services create a connection (pooled BasicDataSource) at the beginning and commit after all DAOs ware successfully called.

Now i want to test them via Spring junit, but the "commit" at the end is not rolled back (even with @Transactional).

how can this be done (I have read that spring encapsules the methods into one transaction and rolls it back)?

@RunWith(SpringJUnit4ClassRunner.class)
//@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class })
@ContextConfiguration(locations = { "classpath:TestProject-spring-test.xml" })
@Transactional
public abstract class BaseTest {

    @Autowired
    protected BasicDataSource dataSource;

    @Autowired
    protected JdbcTemplate jdbc;


    @Test
    @Rollback(true)
    public void testTransactional() throws SQLException{
        jdbc.execute("INSERT INTO test (pk) VALUES (0)");

        Connection con = dataSource.getConnection();
        Statement stmt = con.createStatement();
        stmt.executeUpdate("INSERT INTO test (pk) VALUES (1)");
        con.commit();
        con.close();
    }

}

The jdbc.execute is rolled back, but the Connection retrieved by datasource is not rolled back.

how can i force a rollback even if I commit a Connection?

1
Well of course it won't... You are obtaining a connection yourself outside of the scope of spring. So for the spring managed connection there is nothing to rollback. - M. Deinum
how then can I get a connection by spring and give it back? - Niko
Use the JdbcTemplate... What is it you are trying to test? - M. Deinum
Does JdbcTemplate support connection pooling? I often have a method which creates a connection and passes it to some sub methods. at the end the connection is closed. now I want to use Spring and migrate this "old" logic. - Niko
JdbcTemplate doesn't care about that, it uses a datasource. When using properly configured transactions it uses a single connection for the whole transaction. Unless you start messing around with obtaining connections yourself outside the transaction like you are doing in your test. - M. Deinum

1 Answers

0
votes

As pointed out by @M.Deinum Spring doesn't know anything about your connection (got directly from your datasource) so you cannot expect it to rollback anything. You should use your spring context (and your spring managed DAOs) to execute your tests. See this example.