hibernate - 需要解释事先冲洗的必要性以避免在使用 Spring 进行测试时出现误报吗?

标签 hibernate spring testing jpa false-positive

spring documentation regarding testing ,它指出:

Avoid false positives when testing ORM code

When you test code involving an ORM framework such as JPA or Hibernate, flush the underlying session within test methods which update the state of the session. Failing to flush the ORM framework's underlying session can produce false positives: your test may pass, but the same code throws an exception in a live, production environment. In the following Hibernate-based example test case, one method demonstrates a false positive and the other method correctly exposes the results of flushing the session.

有人可以解释为什么我需要调用 flush 吗?

最佳答案

好吧,你实际上跳过了有趣的部分,例子 :) 这里是:

// ...

@Autowired
private SessionFactory sessionFactory;

@Test // no expected exception!
public void falsePositive() {
    updateEntityInHibernateSession();
    // False positive: an exception will be thrown once the session is
    // finally flushed (i.e., in production code)
}

@Test(expected = GenericJDBCException.class)
public void updateWithSessionFlush() {
    updateEntityInHibernateSession();
    // Manual flush is required to avoid false positive in test
    sessionFactory.getCurrentSession().flush();
}

// ...

这个例子试图说明的是,除非你真的 flush session (A.K.A. 一级缓存)将内存中的变化与数据库同步,否则你并不是在真正测试数据库集成并且可能不会测试真正的预期行为或遗漏问题。

例如,数据库可能会因为违反约束而返回错误,如果您不访问数据库,您将不会表现出这种正确的行为,如 falsePositive()上面的测试方法。此测试方法应该会失败,或者预计会出现异常但只会通过。另一方面,另一种带有 flush 的测试方法确实测试了真实的行为。因此需要 flush

关于hibernate - 需要解释事先冲洗的必要性以避免在使用 Spring 进行测试时出现误报吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3562399/

相关文章:

asp.net-mvc - 在 Asp.net MVC 项目中是否可以稍后添加测试项目?

Java 处理 Spring Data 原生查询中的 NPE 投影

java - JPA 存储库方法 List<Integer> 返回结果为 List<BigDecimal> 为什么?

java - 组织.hibernate.MappingException : No Dialect mapping for JDBC type: 2002

java - 是否可以自动生成 Java 类的 Hibernate 映射?

java - 在 Spring Boot 中使用 RestTemplate 时,Long 值始终为 null

algorithm - 归并与插入排序的实证分析——难点

java - 使用 Spring 和 Spring Roo 的多种形式

spring - @Qualifier 和 @Resource 在 Spring 测试框架下运行测试用例时不起作用

javascript - Postman 测试 - 使用 http 状态进行调节