[hibernate-dev] Making tests nicer with lambdas
Hardy Ferentschik
hardy at hibernate.org
Fri Apr 25 06:57:51 EDT 2014
On 25 Jan 2014, at 10:41, Gunnar Morling <gunnar at hibernate.org> wrote:
> I've played around a bit with the idea of using Java 8 lambdas to make
> tests easier to write and read. We have many tests which open a session and
> TX, do some stuff, commit, open a new TX (and/or session), do some
> assertions and so on:
>
> Session session = openSession();
> Transaction transaction = session.beginTransaction();
>
> // heavy testing action...
> transaction.commit();
> session.clear();
>
> transaction = session.beginTransaction();
>
> // load, assert...
> transaction.commit();
> session.clear();
>
> The same could look like this using Java 8 lambdas:
>
> Foo foo = inTransactionWithResult( (session, tx) -> {
> // heavy testing action...
> } );
>
> inTransaction( (session, tx) -> {
> // load, assert...
> } );
>
> Extracting the session/TX handling removes quite some clutter and focuses
> more on the actual testing logic.
Makes things a but nicer. A bit of syntactic sugger. Not sure though whether it is enough to
switch to JDK 8 for building.
> It also avoids problems due to dangling
> transactions e.g. in case of assertion failures as the TX handling is done
> in a finally block in inTransaction().
A lot of this should already be taken care of by the CustomRunner we use to execute the tests.
—Hardy
More information about the hibernate-dev
mailing list