Is Hamcrest Patterns Acceptable in Non-Research Code?

I am trying to find the final answer to using Hamcrest matches in non-test code. I did a bit of work and I have some contrasting quotes:

  • Hambrest on Wikipedia :

    Hamcrest is a framework that helps you write software tests in the Java programming language. [snip] These matches are used as part of unit tests such as JUnit 2 and jMock.

  • Humbrest on Github :

    Hamcrest is a match library that can be combined to create flexible expressions in tests .

  • Hambrest on Google Code :

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

Personally, I associate Matchers with tests, so I try to avoid using them outside of tests. However, I do not see any restrictions that would prevent their use outside the testing area.

Does this then mean personal preference?

+5
source share
2 answers

I have used Hamcrest in non-test code several times so far. I mainly use it when I want to check different conditions on the same object to get a report on which conditions failed for what reasons. Then, individual conditions are presented as different objects, which also have some other good effects. For example, checking the configuration of an application can produce results whose data is supported for which operations.

The reasons why I especially use hamcrest for this type of task:

  • it was developed for this (testing conditions are not only met in the test code)
  • it does not bring additional dependencies along
  • widely known as many use it already for test code
  • has an easy to use and small API
  • expands easily and supports composition very well

Finally, it comes down to choosing the right tool for the job. For example, Bean validation can be used to perform relatively similar tasks. Then you need to make an informed decision, which also includes the requirements of the development process and environment.

Also, using matches is a good way to use Tell, not Ask. You can pass a matching method to a method to indicate which return value you expect to return. If the object in question does not correspond to this coincidence, then an exception with a good description of the error can be immediately excluded.

Also, comparing the use of matches with Predicate java 8, developers are able to provide a description, but the disadvantage is that they are not the functional interface itself.

+5
source

It can be used in non-test code. For instance. LambdaJ library supports Hamcrest combinations: https://code.google.com/p/lambdaj/wiki/LambdajFeatures

+2
source

Source: https://habr.com/ru/post/1206599/


All Articles