JUnit – assertThat (Hamcrest) – part 3

Ok, it’s time to continue our series of examples Hamcrest matchers usage. Previous blog posts can be found here (part 1part 2).

  • endsWith()

Creates a matcher that matches if the examined String ends with the specified String.

   @Test
    public void endsWithExample() {

        assertThat("Let's test endsWith matcher", endsWith("matcher"));
    }

 

  • equalTo()

Creates a matcher that matches when the examined object is logically equal to the examined object.

   @Test
    public void equalToValueExample() {

        String testValue = "text";

        assertThat(testValue, equalTo("text"));
    }

 

equalTo() can also be used on Arrays in which case it will check the length of the Array and ensure that all the values in the input test array are logically equal to the values of the specified array.

   @Test
    public void equalToArrayExample() {

        assertThat(new String[] {"Jon", "Paul"}, equalTo(new String[] {"Jon", "Paul"}));
    }

 

  • equalToIgnoringCase()

Creates a matcher of String that matches when the examined string is equal to the specified expectedString, ignoring case.

   @Test
    public void equalToIgnoringCaseExample() {

        String testValue = "TeXt";

        assertThat("text", equalToIgnoringCase(testValue));
    }

 

  • equalToIgnoringWhiteSpace()

Creates a matcher of String that matches when the examined string is equal to the specified expected String when whitespace differences are (mostly) ignored. To be exact, the following whitespace rules are applied:

  1. all leading and trailing whitespace of both the expected String and the examined string are ignored
  2. any remaining whitespace, appearing within either string, is collapsed to a single space before comparison
   @Test
    public void equalToIgnoringWhiteSpaceExample() {

        String testValue = "all leading    and trailing whitespace of both    the       expectedString and     the examined string   are       ignored    ";

        // Then
        assertThat(testValue, equalToIgnoringWhiteSpace("all leading and trailing whitespace of both the expectedString and the examined string are ignored"));
    }

 

  • greaterThan()

Creates a matcher of Comparable object that matches when the examined object is greater than the specified value, as reported by the compareTo method of the examined object.

   @Test
    public void greaterThanExample() {

        Integer testValue = 5;

        assertThat(6, is(greaterThan(testValue)));
    }

 

  • greaterThanOrEqualTo()

Creates a matcher of Comparable object that matches when the examined object is greater than or equal to the specified value, as reported by the compareTo method of the examined object.

    @Test
    public void greaterThanOrEqualToExample() {

        Double testValue = 5.5;

        assertThat(5.5, is(greaterThanOrEqualTo(testValue)));
    }

 

  • hasEntry()

Creates a matcher for Maps matching when the examined Map contains at least one entry whose key equals the specified key and whose value equals the specified value.

  @Test
    public void hasEntryExample() {

        Map<Integer, String> myMap = new HashMap<>();
        myMap.put(1, "value");

        assertThat(myMap, hasEntry(1, "value"));
    }

 

  • hasKey()

Creates a matcher for Maps matching when the examined Map contains at least one key that satisfies the specified matcher.

  @Test
    public void hasKeyExample() {

        Map<Integer, String> myMap = new HashMap<>();
        myMap.put(1, "value");
        myMap.put(2, "anotherValue");

        assertThat(myMap, hasKey(1));

 

  • hasValue()

Creates a matcher for Maps matching when the examined Map contains at least one value that is equal to the specified value.

   @Test
    public void hasValueExample() {

        Map<Integer, String> myMap = new HashMap<>();
        myMap.put(1, "value");
        myMap.put(2, "anotherValue");

        assertThat(myMap, hasValue("anotherValue"));
    }

 

  • hasItem()

Creates a matcher for Iterables that only matches when a single pass over the examined Iterable yields at least one item that is equal to the specified item. Whilst matching, the traversal of the examined Iterable will stop as soon as a matching item is found.

   @Test
    public void hasItemExample() {

        List<Integer> testList = Arrays.asList(50, 60, 4, 67, 9);

        assertThat(testList, hasItem(67));

    }

 

  • hasItems()

Creates a matcher for Iterables that matches when consecutive passes over the examined Iterable yield at least one item that is equal to the corresponding item from the specified items. Whilst matching, each traversal of the examined Iterable will stop as soon as a matching item is found.

    @Test
    public void hasItemsExample() {

        List<Integer> testList = Arrays.asList(50, 60, 4, 67, 9);

        assertThat(testList, hasItems(67, 60));
    }

 

  • hasSize()

Creates a matcher for Collections that matches when the size() method returns a value equal to the specified size.

   @Test
    public void hasSizeExample() {

        List<Integer> testList = Arrays.asList(50, 60, 4, 67, 9);

        assertThat(testList, hasSize(5));
    }

 

  • instanceOf()

Creates a matcher that matches when the examined object is an instance of the specified type.

   @Test
    public void instanceOfExample() {

        Object integer = 5;

        assertThat(integer, instanceOf(Integer.class));
    }

 

 

JUnit – assertThat (Hamcrest) – part 2

Let’s continue (you can find Hamcrest matchers – part 1 here) our series of examples how to write JUnit test with Hamcrest matchers usage.

  • comparesEqualTo()

Creates a matcher of a Comparable object that matches when the examined object is equal to the specified value, as reported by the compareTo method of the examined object. The value which, when passed to the compareTo method of the examined object, should return zero.

   @Test
    public void comparesEqualToExample() {

        assertThat(5, comparesEqualTo(5));
    }

 

  • contains()

Various matchers which can be used to check if an input Iterable contains values. The order of the values is important and the number of items in the Iterable must match the number of values being tested.

Test if the input list contains all of the values, the order of items is important.

  @Test
    public void containsItemsExample() {
        // Given
        List<String> names = Arrays.asList("Jon", "Peter", "Paul");

        // Then
        assertThat(names, contains("Jon", "Peter", "Paul"));
    }

Test if the input list contains items which match all of the matchers in the input matchers list, the order of items is important.

   @Test
    public void containsAllMatchersExample() {
        // Given
        List<String> strings = Arrays.asList("Jon", "Peter", "Paul");

        // Then
        List<org.hamcrest.Matcher<? super String>> matchers = new ArrayList<>();
        matchers.add(startsWith("Jo"));
        matchers.add(endsWith("ter"));
        matchers.add(equalTo("Paul"));
        assertThat(strings, contains(matchers));
    }

 

  • containsInAnyOrder()

This one is like contains() but as the name suggest the order of items is not important.

   @Test
    public void containsItemsInAnyOrderExample() {
        // Given
        List<String> names = Arrays.asList("Jon", "Peter", "Paul");

        // Then
        assertThat(names, containsInAnyOrder("Peter", "Jon", "Paul"));
    }

   @Test
    public void containsAllMatchersInAnyOrderExample() {
        // Given
        List<String> strings = Arrays.asList("Jon", "Peter", "Paul");

        // Then
        List<org.hamcrest.Matcher<? super String>> matchers = new ArrayList<>();
        matchers.add(endsWith("ter"));
        matchers.add(startsWith("Jo"));
        matchers.add(equalTo("Paul"));
        assertThat(strings, containsInAnyOrder(matchers));
    }

 

  • containsString()

A matcher that matches if the examined String contains the specified String anywhere.

   @Test
    public void containsStringExample() {
        // Given
        String testValue = "A very short sentence.";

        // Then
        assertThat(testValue, containsString("nt"));
    }

 

  • empty()

A matcher for Collections matching examined collections whose isEmpty method returns true.

    @Test
    public void emptyMatcherExample() {
        // Given
        Queue<String> collectionToTest = new LinkedList<>();

        // Then
        assertThat(collectionToTest, is(empty()));
    }

 

  • emptyArray()

A matcher for arrays that matches when the length of the array is zero.

   @Test
    public void emptyArrayMatcherExample() {
        // Given
        Integer[] arrayToTest = new Integer[0];

        // Then
        assertThat(arrayToTest, is(emptyArray()));
    }

 

  • emptyCollectionOf()

A matcher for Collections matching examined collections whose isEmpty method returns true.

   @Test
    public void emptyCollectionOfMatcherExample() {
        // Given
        Set<String> collectionToTest = new HashSet<>();

        // Then
        assertThat(collectionToTest, is(emptyCollectionOf(String.class)));
    }

 

  • emptyIterable()

A matcher for Iterables matching examined iterable that yield no items.

  @Test
    public void emptyIterableMatcherExample() throws Exception {
        // Given
        ArrayList<String> collectionToTest = new ArrayList<>();

        // Then
        assertThat(collectionToTest, is(emptyIterable()));
    }

 

  • emptyIterableOf()

A matcher for Iterables matching examined iterable that yield no items and is of the given type.

   @Test
    public void emptyIterableOfMatcherExample() throws Exception {
        // Given
        ArrayList<String> collectionToTest = new ArrayList<>();

        // Then
        assertThat(collectionToTest, is(emptyIterableOf(String.class)));
    }

 

 

JUnit – assertThat (Hamcrest) – part 1

Hamcrest is a framework for creating matcher objects. These matcher objects are predicates and are used to write rules which can be satisfied under certain conditions. They are most often used in testing. Hamcrest lets us step beyond simple JUnit asserts and enables us to craft very specific and readable verification code. Hamcrest has the target to make tests as readable as possible. In general, the Hamcrest error messages are also much easier to read. Using Hamcrest matchers also provides more type safety as these matchers uses generics.

Simple Matchers

  • any()
@Test
public void anyMatcherExample() {

    int age = 30;
    assertThat(age, is(any(Integer.class)));        
}
  • anything()
@Test
public void anythingMatcherExample() {

    Integer age = 30;
    assertThat(age, is(anything()));
}
  • arrayContaining()

Does the array contain all given items in the order in which they are input to the matcher?

@Test
public void arrayContainingMatcherExample() {

    String[] names = {"Jon", "Peter", "Paul"};
    assertThat(names, is(arrayContaining("Jon", "Peter", "Paul")));
}
  • arrayContainingInAnyOrder()

Does the array contain all the given items? Length of the array must match the number of matchers, but their order is not important.

@Test
public void arrayContainingInAnyOrderMatcherExample() {

    String[] names = {"Jon", "Peter", "Paul"};
    assertThat(names, is(arrayContainingInAnyOrder("Peter", "Paul", "Jon")));
}
  • arrayWithSize()

Does the input array have exactly the specified length?

@Test
public void arrayWithSizeMatcherExample() {

    String[] names = {"Jon", "Peter", "Paul"};
    assertThat(names, is(arrayWithSize(3)));
}
@Test
public void arrayWithSizeGreaterThanMatcherExample() {

    String[] names = {"Jon", "Peter", "Paul"};
    assertThat(names, is(arrayWithSize(greaterThan(2))));
}
  • closeTo()

Matcher which can be used with either Double or BigDecimal to check if a value is within a specified error margin of an expected value.

@Test
public void closeToDoubleMatcherExample() {

    Double temperature = 25.5;
    assertThat(temperature, closeTo(25.0, 0.5));
}
@Test
public void closeToBigDecimalMatcherExample() {

    BigDecimal totalValue = new BigDecimal(234.00);
    assertThat(totalValue, closeTo(new BigDecimal(230.0), new BigDecimal(5)));
}

 

 

 

 

JUnit – basics introduction

The JUnit framework

JUnit (http://junit.org/) in version 4.x is a test framework which uses annotations to identify methods that specify a test.

A unit test is a fundamental test to quickly assess whether the result of a computation can possibly go wrong or not. It is a straightforward check to verify the basis of the computation result. To define a method as a unit test, you annotate it with the @org.junit.Test annotation. You use an assert method, provided by JUnit or another assert framework, to check an expected result versus the actual result.

Recommended practice

Generally, we don’t mix production code with the test code, so unit tests are kept in the same project, but under a different directory or source folder.

In widespread use is to use the name of the class under test and to add the “Test” suffix to the test class.

As a general rule, a test name should explain what the test does. If that is done correctly, it helps to avoid reading the actual implementation.

JUnit code constructs

JUnit 4.x uses annotations to mark methods as test methods and to configure them.

The @Test annotation signifies a test. We can annotate any public method with @Test to make it a JUnit test method.

JUnit 4 defines two method-level annotations, @BeforeClass and @AfterClass, for public static methods. Being static, they get executed only once per test class. Any public static method annotated with @BeforeClass gets executed prior to the first test, and any public static method annotated with @AfterClass gets executed following the last test.

Other mostly used JUnit annotations:

@Test (expected = Exception.class) – Fails if the method does not throw the named exception.

@Before – This method is executed before each test. It is used to prepare the test environment (e.g., read input data, initialize the class).

@After – This method is executed after each test. It is used to cleanup the test environment (e.g., delete temporary data, restore defaults).

@Ignore – Sometimes you want to temporarily disable a test or a group of tests. Methods annotated with @Test that are also annotated with @Ignore will not be executed as tests. Also, you can annotate a class containing test methods with @Ignore and none of the containing tests will be executed. It is best practice to provide the optional description, why the test is disabled.

@Ignore("not ready yet")
public class SimpleJUnitExample {

    @BeforeClass
    public static void beforeClass() {
        System.out.println("Before Class is invoked");
    }

    @Before
    public void before() {
        System.out.println("Before is invoked");
    }

    @After
    public void after() {
        System.out.println("After is invoked");
    }

    @Test
    public void testMethod() {
        System.out.println("testMethod is invoked");
    }

    @Test
    public void anotherTestMethod() {
        System.out.println("anotherTestMethod is invoked");
    }

    @Test
    @Ignore("not ready test yet")
    public void notTestableYet() {
        System.out.println("not testable yet, should be ignored");
    }

    @AfterClass
    public static void afterClass() {
        System.out.println("After Class is invoked");
    }

}

And result is:

Before Class is invoked

not ready test yetBefore is invoked
anotherTestMethod is invoked
After is invoked
Before is invoked
testMethod is invoked
After is invoked
After Class is invoked

As you probably noticed tests execution order is different from the order of test methods.By design, JUnit does not specify the execution order of test method invocations. Well-written test code would not assume any order.

From version 4.11, JUnit will by default use a deterministic, but not predictable, order(MethodSorters.DEFAULT). To change the test execution order simply annotate your test class using @FixMethodOrder and specify one of the available MethodSorters:

@FixMethodOrder(MethodSorters.JVM): Leaves the test methods in the order returned by the JVM. This order may vary from run to run.

@FixMethodOrder(MethodSorters.NAME_ASCENDING): Sorts the test methods by method name, in lexicographic order.

Assert statements

Verifying an expectation with an assertion. JUnit provides static methods to test for certain conditions via the Assert`class. These assert statementstypically start with `assert . They allow you to specify the error message, the expected and the actual result. An assertion method compares the actual value returned by a test to the expected value. It throws an AssertionExceptionif the comparison fails.

Mostly used assert methods:

fail(message) – Let the method fail. Might be used to check that a certain part of the code is not reached or to have a failing test before the test code is implemented. The message parameter is optional.

assertTrue([message,] boolean condition) – Asserts that a condition is true.

assertFalse([message,] boolean condition) – Asserts that a condition is false.

assertEquals([message,] expected, actual) – Asserts that two objects are equal. If they are not, an AssertionError is thrown with the given message. If expected and actual are null, they are considered equal. For arrays the reference is checked not the content of the arrays.

assertNull([message,] object) – Checks that the object is null.

assertNotNull([message,] object) – Checks that the object is not null.

assertSame([message,] expected, actual) – Checks that both variables refer to the same object.

assertNotSame([message,] expected, actual) – Checks that both variables refer to different objects.

Examining exception handling

In a JUnit test, when a test method throws an exception, the test fails, and the test method marks the test as erroneous. We should be allowed to unit test the exceptional condition such that an API takes two objects and throws an exception if any argument is passed as null . If we pass
a null value to the API, the test fails with an error, but actually, an exception is not an error. Rather, it is desirable, and the test should fail if the API doesn’t throw an exception.

JUnit 4 provides a mechanism to handle the preceding situation.
The @Test annotation takes an expected=<<Exception class name>>.class argument.
When we annotate a test method with @Test and pass an expected exception to the annotation, but during execution, the expected exception doesn’t match the real exception thrown from the test method or the test method doesn’t throw an exception, the test fails.

@Test(expected=RuntimeException.class)
public void test_exception_condition() {
throw new RuntimeException();
}

This exception handling mechanism doesn’t allow you to verify the error message. JUnit 4 provides several other mechanisms that are usually considered to be better solutions, such as @Rule , an ExpectedException rule that lets you examine the message as well as the type.

Test suits

A test suite groups and executes multiple tests. To run multiple tests together, we need a test suite. To achieve this, JUnit 4 offers the Suite.class class and the @Suite.SuiteClasses annotation. This annotation accepts a comma-separated array of test classes. Add a Java class named TestSuite and annotate it with @RunWith(Suite.class). As a result, the suite runner will be responsible for executing the test class. Annotate the TestSuite class with @Suite.SuiteClasses and pass a comma-separated array of other test classes, such as ({ ClientTest.class,
ClientOrder.class, ShoppingBasket.class }) .

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ AssertTest.class, TestExecutionOrder.class, Assumption.class })
   public class TestSuite {
}

When we execute the TestSuite class, it, in turn, executes all the test classes passed to the @Suite.SuiteClasses annotation.