Spring启动,事务测试后不回滚

时间:2016-06-07 18:59:38

标签: unit-testing spring-boot spring-data spring-data-jpa spring-transactions

我正在为我的服务编写单元测试。问题是,在测试完成后,事务不会通过spring boot自动回滚。

这是我的测试:

@SpringApplicationConfiguration(classes = { TestApplicationConfiguration.class, TestDataSourceConfiguration.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class BoardServiceTest {

@Autowired
    private UserService userService;

    @Autowired
    private CardService cardService;

    @Autowired
    private BoardCardService boardCardService;

    @Autowired
    private BoardService boardService;

    @Autowired
    private CommonBoardService commonBoardService;

    @Autowired
    private AuthorityService authorityService;

    @Test(expected = CommonException.class)
    @Transactional
    public void testCreateBoardStatusAFK() {
        final User admin = userService.findUserById(1l);
        admin.setCurrentBoard(null);

        Board board = boardService.startBoard(admin);
        assertEquals(board, admin.getCurrentBoard());

        // Board has status IN_PROGRESS, current time < timeToComplete
        board.setSelectedCardsCount(boardService.getDefaultCardsToSelectCount() - 1);
        board.setTimeToComplete(DateUtils.addHours(new Date(), boardService.getDefaultMinsToComplete()));
        board = commonBoardService.save(board);
        board = boardService.startBoard(admin);
        assertEquals(admin.getCurrentBoard().getStatus(), Board.IN_PROGRESS);

        // Board has status IN_PROGRESS, current time > timeToComplete
        board.setTimeToComplete(DateUtils.addHours(new Date(), -1));
        board = commonBoardService.save(board);
        board = boardService.startBoard(admin);

        assertEquals(admin.getCurrentBoard().getStatus(), Board.AFK);
    }
}

测试执行后,测试数据库中的相应表将填入新记录。

请告诉我,如何解决这个问题?

更新:

以下是我在测试期间调用的服务方法的实现:

   @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Board update(Board board, Date finishedDate, Integer status) {
        board.setStatus(status);
        board.setFinishedDate(finishedDate);

        return boardRepository.save(board);
    }

您可以看到,调用此方法时会打开新事务。 在我的调试控制台中,我在更新完成后看到以下信息:

Hibernate: select nextval ('boards_id_seq')
Hibernate: insert into boards (created_date, updated_date, cards_to_hold, cards_to_select, finished_date, holded_cards_count, selected_cards_count, started_date, status, time_to_complete, time_to_next_board, user_id, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

我不明白,为什么hibernate在db中创建新实体,虽然我正在更新现有实体。 那么,也许这就是这种行为的原因?

1 个答案:

答案 0 :(得分:0)

您需要在事务性注释中提供rollbackFor参数。 @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)默认回滚仅适用于带有Transactional批注的未经检查的异常(RuntimeException或Error的实例)