How to flush data into db inside active spring transaction?

后端 未结 4 2124
谎友^
谎友^ 2020-12-03 03:46

I want to test hibernate session\'s save() method using spring testing framework. @Test method is :

@Test
@Transactional
public void testSave() {
    User ex         


        
4条回答
  •  心在旅途
    2020-12-03 04:09

    Finally I stuck to the following solution:

    First, my @Test methods are not running within spring @Transactional support. See this article to know how dangerous it may be. Next, instead of using @Repository beans inside @Test methods I autowire @Service beans which use @Transactional annotation. The miracle is that @Test method like this

    @Test
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void testSave() {
        Answer created = createAnswer();
        Long generatedId = answerService.save(created);
    //at this moment answer is already in db
        Answer actual=getAnswerById(generatedId);
    ... }
    

    puts my Answer object into database (just after answerService.save(created);) and method getAnswerById goes to DB and extracts it to check if save was correct.
    To eliminate changes made to database in @Test method I recreate database by JdbcTestUtils.executeSqlScript

提交回复
热议问题