Top Related Projects
A programmer-oriented testing framework for Java.
Most popular Mocking framework for unit tests written in Java
AssertJ is a library providing easy to use rich typed assertions
Fluent assertions for Java and Android
Java DSL for easy testing of REST services
TestNG testing framework
Quick Overview
JavaHamcrest is a framework for writing matcher objects, allowing you to declaratively define "match" rules. It is commonly used in unit testing to create more readable and expressive assertions. JavaHamcrest provides a rich set of built-in matchers and allows for easy creation of custom matchers.
Pros
- Improves test readability and expressiveness
- Provides a wide range of built-in matchers for common scenarios
- Allows easy creation of custom matchers
- Integrates well with popular testing frameworks like JUnit
Cons
- Learning curve for developers new to the matcher concept
- Can make simple assertions more verbose
- May introduce additional complexity in some cases
- Requires adding an extra dependency to your project
Code Examples
- Basic assertion using Hamcrest:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
// ...
assertThat(actualValue, equalTo(expectedValue));
- Combining matchers:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
// ...
List<String> fruits = Arrays.asList("apple", "banana", "orange");
assertThat(fruits, allOf(
hasSize(3),
hasItem("banana"),
not(hasItem("grape"))
));
- Custom matcher:
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
public class IsEvenNumber extends TypeSafeMatcher<Integer> {
@Override
protected boolean matchesSafely(Integer number) {
return number % 2 == 0;
}
@Override
public void describeTo(Description description) {
description.appendText("an even number");
}
public static IsEvenNumber evenNumber() {
return new IsEvenNumber();
}
}
// Usage:
assertThat(4, evenNumber());
Getting Started
To use JavaHamcrest in your project, add the following dependency to your Maven pom.xml
:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
For Gradle, add this to your build.gradle
:
testImplementation 'org.hamcrest:hamcrest:2.2'
Then, in your test classes, import the necessary static methods:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
Now you can start using Hamcrest matchers in your tests!
Competitor Comparisons
A programmer-oriented testing framework for Java.
Pros of JUnit4
- More comprehensive testing framework with a wider range of features
- Extensive documentation and community support
- Built-in test runners and annotations for easy test organization
Cons of JUnit4
- Larger codebase and potentially more complex setup
- Less focused on matcher-based assertions compared to JavaHamcrest
- May require additional dependencies for certain functionalities
Code Comparison
JavaHamcrest:
assertThat(actualValue, is(equalTo(expectedValue)));
assertThat(list, hasItem("element"));
assertThat(object, hasProperty("propertyName", equalTo(expectedValue)));
JUnit4:
assertEquals(expectedValue, actualValue);
assertTrue(list.contains("element"));
assertEquals(expectedValue, object.getPropertyName());
Summary
JUnit4 is a more comprehensive testing framework with broader functionality, while JavaHamcrest focuses on providing expressive and readable matcher-based assertions. JUnit4 offers built-in test runners and annotations, making it easier to organize and execute tests. However, it may have a steeper learning curve due to its larger codebase and feature set.
JavaHamcrest excels in creating readable and expressive assertions using its matcher library. It provides a more focused approach to assertions, which can lead to more maintainable and self-documenting test code. However, it may require additional setup or integration with other testing frameworks for a complete testing solution.
Ultimately, the choice between the two depends on the specific needs of the project and the development team's preferences for test writing and organization.
Most popular Mocking framework for unit tests written in Java
Pros of Mockito
- More comprehensive mocking framework, allowing for stubbing, verification, and argument capturing
- Easier to read and write test code with its fluent API
- Better integration with popular testing frameworks like JUnit
Cons of Mockito
- Steeper learning curve due to more features and complexity
- May encourage overuse of mocking, potentially leading to brittle tests
- Requires more setup for certain scenarios compared to Hamcrest's simplicity
Code Comparison
Mockito:
List mockedList = mock(List.class);
when(mockedList.get(0)).thenReturn("first");
assertEquals("first", mockedList.get(0));
verify(mockedList).get(0);
Hamcrest:
List<String> list = Arrays.asList("foo", "bar");
assertThat(list, hasSize(2));
assertThat(list, hasItem("foo"));
assertThat(list, not(hasItem("baz")));
Summary
Mockito is a more powerful mocking framework with a wider range of features, while JavaHamcrest focuses on providing expressive matchers for assertions. Mockito is better suited for complex mocking scenarios, while Hamcrest excels in creating readable assertions. The choice between the two depends on the specific testing needs of the project.
AssertJ is a library providing easy to use rich typed assertions
Pros of AssertJ
- More fluent and readable syntax with method chaining
- Rich set of assertions for various types, including collections and exceptions
- Better IDE auto-completion support
Cons of AssertJ
- Steeper learning curve for developers familiar with JUnit assertions
- Larger library size compared to Hamcrest
Code Comparison
AssertJ:
assertThat(list).hasSize(3)
.contains("A", "B")
.doesNotContain("X");
JavaHamcrest:
assertThat(list, hasSize(3));
assertThat(list, hasItems("A", "B"));
assertThat(list, not(hasItem("X")));
Key Differences
- AssertJ provides a more expressive and fluent API
- JavaHamcrest uses separate assertions for each check
- AssertJ offers more specific assertions for different types
- JavaHamcrest relies on matchers, which can be combined for complex assertions
Use Cases
- AssertJ: Projects prioritizing readability and extensive assertion options
- JavaHamcrest: Projects requiring lightweight libraries or preferring matcher-based assertions
Both libraries are widely used in Java testing, with AssertJ gaining popularity for its intuitive syntax and comprehensive assertion set, while JavaHamcrest remains a solid choice for its simplicity and flexibility.
Fluent assertions for Java and Android
Pros of Truth
- More fluent and readable assertion syntax
- Better error messages with clear failure descriptions
- Supports custom types and extensions more easily
Cons of Truth
- Less widely adopted compared to Hamcrest
- Requires learning a new API for those familiar with Hamcrest
- May have fewer third-party extensions available
Code Comparison
Truth:
assertThat(actual).isEqualTo(expected);
assertThat(list).containsExactly(1, 2, 3).inOrder();
assertThat(exception).hasMessageThat().contains("error");
JavaHamcrest:
assertThat(actual, is(equalTo(expected)));
assertThat(list, contains(1, 2, 3));
assertThat(exception.getMessage(), containsString("error"));
Summary
Truth offers a more modern and readable syntax with improved error messages, making it easier to write and maintain tests. However, JavaHamcrest has been around longer and has wider adoption in the Java ecosystem. Both libraries provide powerful assertion capabilities, but Truth's fluent API and custom type support give it an edge in terms of usability and extensibility. The choice between the two often comes down to personal preference and project requirements.
Java DSL for easy testing of REST services
Pros of rest-assured
- Specifically designed for testing RESTful APIs, offering a domain-specific language for HTTP requests
- Integrates seamlessly with JSON and XML parsing, simplifying response validation
- Supports both BDD and non-BDD styles of testing
Cons of rest-assured
- Limited to API testing, while Hamcrest is a general-purpose matcher library
- Steeper learning curve due to its extensive API and features
- May be overkill for simple API tests or projects not focused on REST testing
Code Comparison
rest-assured:
given()
.param("key", "value")
.when()
.get("/api/resource")
.then()
.statusCode(200)
.body("field", equalTo("expected"));
JavaHamcrest:
assertThat(response.getStatusCode(), is(200));
assertThat(response.getBody().getField(), equalTo("expected"));
Key Differences
- Rest Assured provides a fluent API specifically for REST testing, while JavaHamcrest offers general-purpose matchers
- Rest Assured includes built-in support for request building and response parsing
- JavaHamcrest is more flexible and can be used in various testing scenarios beyond API testing
Use Cases
- Choose Rest Assured for comprehensive REST API testing projects
- Opt for JavaHamcrest for general assertion needs or when working with diverse testing requirements
TestNG testing framework
Pros of TestNG
- More comprehensive testing framework with support for parallel execution and data-driven testing
- Built-in reporting capabilities and integration with various tools
- Flexible test configuration using XML files or annotations
Cons of TestNG
- Steeper learning curve compared to JavaHamcrest
- More complex setup and configuration required
- May be overkill for simple unit testing scenarios
Code Comparison
TestNG example:
@Test(groups = {"unit"})
public void testAddition() {
Calculator calc = new Calculator();
Assert.assertEquals(calc.add(2, 3), 5);
}
JavaHamcrest example:
@Test
public void testAddition() {
Calculator calc = new Calculator();
assertThat(calc.add(2, 3), is(equalTo(5)));
}
While both frameworks can be used for assertions, TestNG provides a more comprehensive testing framework with additional features, whereas JavaHamcrest focuses primarily on creating readable and expressive assertions. TestNG is better suited for larger projects with complex testing requirements, while JavaHamcrest excels in improving the readability of test assertions and can be easily integrated with other testing frameworks.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Java Hamcrest
What is Hamcrest?
Hamcrest is a library of matchers, which can be combined in to create flexible expressions of intent in tests. They've also been used for other purposes.
The tutorial is good place to see how Hamcrest can be used.
Downloads
You can obtain Hamcrest binaries from maven central. If you are using build tooling such as Maven, Gradle, etc, you can simply add a dependency declaration to your build definition. Learn more at Hamcrest Distributables.
Documentation
Documentation can be found on the Hamcrest site. For a detailed list of recent changes, see CHANGES.md
Reporting Bugs/Issues
If you find an issue with Java Hamcrest, please report it via the GitHub issue tracker, after first checking that it hasn't been raised already.
Build from Source
Building Hamcrest from source requires a minimum of JDK 1.8.
Clone the repository, and from the top level directory in the repo workspace run the following command:
./gradlew clean build javadoc
This will download the correct version of Gradle, do a full clean build,
run all tests and (if successful) package the compiled classes in a jar
file. The resulting look under the hamcrest/build/libs
directory.
Acknowledgements
Developers:
- Joe Walnes
- Nat Pryce
- Steve Freeman
Contributors:
- Robert Chatley
- Tom White
- Neil Dunn
- Dan North
- Magne Rasmussen
- David Saff
- Tom Denley
- Joe Schmetzer
Also, thanks to everyone who has worked on DynaMock, nMock, jMock, EasyMock and MiniMock! These libraries inspired Hamcrest.
Top Related Projects
A programmer-oriented testing framework for Java.
Most popular Mocking framework for unit tests written in Java
AssertJ is a library providing easy to use rich typed assertions
Fluent assertions for Java and Android
Java DSL for easy testing of REST services
TestNG testing framework
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot