views:

42

answers:

1

I've been finding some unit tests that assume that the results of database queries are in a particular order, yet the query being run doesn't include an order by clause.

I would like to find more of these unit tests, so that I can examine whether the test is at fault in its assumptions, or the code is at fault in its lack of specifying an order.

I'm using java, junit, spring, hibernate, dbunit, jdbc, and postgresql.

One idea I had was to intercept the test queries somewhere, and if a query does not include an order by clause, then capture all the results, and return them in a random order.

Where would be the easiest place to intercept and check the query?

Are there other simple ways of identifying such tests?

+1  A: 

You could take a look at extending Hibernate's EmptyInterceptor, and specifically the onPrepareStatement method. If the sql query passed as the argument doesn't contain an order by clause, you could try adding order by random() to it.

Lauri Lehtinen
That looks like it might work. Is my implementation able to be injected in a sessionFactory bean?
Stephen Denne
If you configure your sessionFactory with Spring's LocalSessionFactoryBean, I'd try making a test-specific config that adds the interceptor there (entityInterceptor property).
Lauri Lehtinen
Thanks, got that working. Now to deal with the errors (eg filtering out select distinct queries)
Stephen Denne