Need explanation on the necessity of a prior flushing to avoid false positives whenTesting with Spring ?

后端 未结 4 1067
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 08:43

In the spring documentation regarding testing, it states:

Avoid false positives when testing ORM code

When you test code involving an

4条回答
  •  孤街浪徒
    2021-01-02 09:06

    Well, you actually skipped the interesting part, the example :) Here it is:

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

    What this example tries to illustrate is that unless you actually flush the session (A.K.A. the first level cache) to sync in-memory changes with the database, you're not really testing the database integration and might not test the real expected behavior or miss a problem.

    For example, the database could return an error because of, say a constraint violation, and if you don't hit the database, you won't exhibit this right behavior, as in the falsePositive() test method above. This test method should fail, or expect an exception but will just pass. On the other hand, the other test method with the flush does test the real behavior. Hence the need to flush.

提交回复
热议问题