Archives de catégorie : terracotta

Skipping a JUnit 4 test using @BeforeClass and a custom hamcrest matcher

Working on a test depending on an external Ldap server (yeah, I know, this sounds bad, but sometimes you just want to make sure your code works against the real thing, not only embedded servers, such as the excellent Apache DS — which I use for other integration tests though!!!) I wanted to make sure this test would not fail when this server was down.
I wanted to tell Junit4 to skip the whole test class if I could not reach the server during an @BeforeClass method.
But how could I tell Junit4 to fail because of a condition in an @BeforeClass method ?

This is when I got 2 precious pieces of advice from my colleague (and hamcrest lover) Chris :

  • use org.junit.Assume.assumeThat(T actual,  Matcher<T> matcher)
  • and eventually create a custom matcher

let’s have a look at the first version of the code :

so if the server is not responding after 5 secs, the test class won’t go further, and return without failing or returning an error; great !

But we can do better than that… what about :

we have now to create the IsReachable matcher :

Did you notice I extended a TypeSafeMatcher and not a plain Matcher ? that way I could avoid casting an Object into an InetAddress in the matches[Safely] method !