需要解释在使用Spring测试时先前冲洗以避免误报的必要性吗?

Jav*_*cky 9 testing spring hibernate jpa false-positive

春季关于测试的文档中,它指出:

在测试ORM代码时避免误报

当您测试涉及ORM框架(如JPA或Hibernate)的代码时,请在更新会话状态的测试方法中刷新基础会话.无法刷新ORM框架的基础会话可能会产生误报:您的测试可能会通过,但相同的代码会在实时生产环境中引发异常.在下面基于Hibernate的示例测试用例中,一个方法演示了误报,另一个方法正确地暴露了刷新会话的结果.

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

Pas*_*ent 3

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

// ...

@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();
}

// ...
Run Code Online (Sandbox Code Playgroud)

此示例试图说明的是,除非您实际上使用flush会话(又称一级缓存)将内存中的更改与数据库同步,否则您并没有真正测试数据库集成,并且可能不会测试真正的预期行为或错过问题。

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