j will
j will

Reputation: 3807

Spring Tests Do Not Store Data in Database

I am running some tests for a game with Spring but for some reason the data in the sql files is not being persisted to the database. Here is my test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {HibernateConfigTest.class})
@Transactional
@Sql(scripts = {"api_routes.sql",
                "profile.sql",
                "status.sql",
                "user.sql",
                "game_token.sql",
                "game.sql",
                "message.sql"},
    executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "delete_data.sql", 
    executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public class GameDaoTest {
    @Autowired
    private GameDao gameDao;

    @Test
    public void testGetGamesByTokenId() {
        assertEquals(36, gameDao.getGamesByTokenId(null).size());
    }
}

When I run the test, the test succeeds. When I go to look at the database, however, during the test none of the data is in there. It appears like Spring is running an in memory database without my knowledge.

Is there anyway to ensure that the data is being persisted to the database?

Upvotes: 0

Views: 1698

Answers (2)

jlars62
jlars62

Reputation: 7353

Add config = @SqlConfig(transactionMode = ISOLATED) to the @SQL annotation for the sql to be run in a separate transaction.

Example:

@Sql(
    scripts = "...",
    config = @SqlConfig(transactionMode = ISOLATED),
    executionPhase = ExecutionPhase.BEFORE_TEST_METHOD
)

Relevant Spring Documentation

Upvotes: 2

joey.enfield
joey.enfield

Reputation: 1229

You can set you transaction to not roll back using

@TransactionConfiguration(defaultRollback = false)

Upvotes: 2

Related Questions