12

I'd like to use hamcrest as sugar framework to use in if statements, not in the unit tests with asserts, but in raw production code.

Something like

if ( isNotEmpty(name) ) return //....

or

if ( isEqual(name, "John")) return //...

Just like AssertThat but without throwing errors, just returning boolean. Is it possible?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Vitamon
  • 538
  • 7
  • 18

4 Answers4

6

It's just Java, it's up to you what you choose to do with it. The Hamcrest homepage says:

Provides a library of matcher objects (also known as constraints or predicates) allowing 'match' rules to be defined declaratively, to be used in other frameworks. Typical scenarios include testing frameworks, mocking libraries and UI validation rules.

Note: Hamcrest it is not a testing library: it just happens that matchers are very useful for testing.

There is also a page on the other frameworks that use Hamcrest.

Community
  • 1
  • 1
skaffman
  • 398,947
  • 96
  • 818
  • 769
5

There's the bool project that provides the following syntax:

if(the(name, is(equalTo("Alex")))) {
...
}
Arend v. Reinersdorff
  • 4,110
  • 2
  • 36
  • 40
  • Wow, that's really impressive! – Vitamon Dec 16 '12 at 17:03
  • 1
    IMHO bool project is a bit overkill for a simple method "the". Even though it provides additional matchers, but these are just duplicates of Hamcrest ones (like allOf, anyOf, either, both, etc) – Jonas Dec 17 '12 at 10:07
5

You can use the matches(value) method of any Matcher instance.

if (equalTo("John").matches(name)) { ... }

To improve the readability, create your own helper method similar to assertThat.

public static <T> boolean checkThat(T actual, Matcher<? super T> matcher) {
    return matcher.matches(actual);
}

...

if (checkThat(name, equalTo("John"))) { ... }

If you come up with a better name than checkThat such as ifTrueThat, please add it in a comment. :)

David Harkness
  • 35,992
  • 10
  • 112
  • 134
5

Following up on David's answer, we are currently doing exactly this, and our helper method is named "the()". This leads to code like:

if(the(name, is(equalTo("John")))) {...}

which gets a little bit lisp-y at the end, but makes it very readable even for clients.

Chris Fell
  • 53
  • 4