繁体   English   中英

用于 Spring Boot 中集成测试的 @Transaction 注解

[英]@Transaction annotation for integration testing in Spring Boot

我在JpaRepository中有以下方法,该方法只需更新该列中具有特定值的每一行的parent_id列。 它在纯 SQL 中完美运行,但在Spring Data 中失败。 我认为这只是由于事务范围的一些问题,因为更新已完成(第一次断言通过)。 只是我看不到 DB 中更改了哪些代码。 我想使用

@Transactional
@Rollback

因为我想这是最佳实践。 有什么办法可以从我的测试方法中查看代码中的内容吗?

@Modifying
@Query("update MovementCategory mc set mc.parentId = :newParentId where mc.parentId = :previousParentId and mc.userId = :userId")
int updateChildrenParentId(@Param("userId") long userId, @Param("previousParentId") long previousParentId, @Param("newParentId") long newParentId);

我创建了一个简单的集成测试,用于检查 DB 中是否正确设置了更改,但它似乎不起作用,我不明白为什么。 我认为这可能是因为事务范围,但我做了一个较小的测试并丢弃了它,所以不知道。 下面是集成测试。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MySpringBootMavenApplication.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
@Transactional
@Rollback
public class MovementCategoryRepositoryIT {

private static final long USER_ID = -1L;

@Autowired MovementCategoryRepository repo;

@Test
public void testUpdateChildrenParentId() {

    long newParentId= -9723854;
    long previousParentId = -1239842;

    MovementCategory mc1 = getFilled(null, "DELETE ME");
    mc1.setParentId(previousParentId);
    mc1 = repo.saveAndFlush(mc1);

    int updates = repo.updateChildrenParentId(USER_ID, previousParentId, newParentId);

    // First assert passes, so there update is done
    assertEquals(1, updates);

    MovementCategory children1 = repo.findOneByIdAndUserId(mc1.getId(), USER_ID);

    // Second one fails
    assertEquals(newParentId, children1.getParentId().longValue());

}

结果:

java.lang.AssertionError: expected:<-9723854> but was:<-1239842>
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:834)
    at org.junit.Assert.assertEquals(Assert.java:645)
    at org.junit.Assert.assertEquals(Assert.java:631)
    at com.ldepablo.repository.MovementCategoryRepositoryIT.testUpdateChildrenParentId(MovementCategoryRepositoryIT.java:171)
    ...

您需要启动事务以显式读取并显式回滚事务,因为 REST 调用位于与测试不同的会话中。 使用此答案中所述的 TransactionTemplate 。

(当然回答太晚了;但这是搜索引擎上的第一次点击)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM