【发布时间】:2016-05-02 16:54:38
【问题描述】:
我在 JpaRepository 中有以下方法,该方法简单地为每一行更新 parent_id 列,并在该列中具有特定值。它在纯 SQL 中完美运行,但在 Spring Data 中失败。我认为这只是事务范围的一些问题,因为更新已完成(第一次断言通过)。只是我看不到数据库中更改了哪些代码。我想使用
@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);
我创建了一个简单的集成测试,用于检查数据库中的更改是否正确设置,但它似乎不起作用,我不明白为什么。我认为这可能是因为事务范围,但我做了一个较小的测试并丢弃它,所以不知道。以下是集成测试。
@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)
...
【问题讨论】:
标签: spring-boot integration-testing spring-data-jpa transactionscope