6.1 asserts

Asserts are special checks that can be inserted at different places in the code. Their task is to determine that something went wrong. Or rather, to check that everything is going as it should. This is “as needed” and they allow you to set it in various ways.

You have already encountered some assertions in the code above. The first one is checking objects for equality. If the objects are not equal, an exception will be thrown and the test will fail.

The order of comparison is important here , because JUnit in the final report will write something like “value 1 received, but 3 was expected”. The general format for such a check is:

assertEquals(standard , meaning)

Example:

@Test
public void whenAssertingEquality () {
    String expected = "3.1415";
    String actual = "3";

    assertEquals(expected, actual);
}

6.2 Methods assertEquals, assertTrue, assertFalse

Below I will list the most popular methods - assertions. By their names it is quite possible to guess how they work. But I'll write a short explanation anyway:

assertEquals Checks that two objects are equal
assertArrayEquals Checks if two arrays contain equal values
assertNotNull Checks if the argument is not null
assertNull Checks if the argument is null
assertNotSame Check that the two arguments are not the same object
assertSame Check that the two arguments are the same object
assertTrue Checks if the argument is true
assertFalse Checks if the argument is false

Some of these methods seem redundant. Why use assertSame(a, b) when you can just write assertTrue(a == b) ?

The point is that assert is a very smart method. It does a lot of useful things, including writing error information to the log . In the first case, it will write that object A was expected, but object B was received. In the second case, it will simply write that true was expected .

When you have hundreds of tests, especially those running on a dedicated test server, having detailed logs can be super helpful. I think you understand what I mean.

Array comparison example:

@Test
public void whenAssertingArraysEquality() {
    char[] expected = {'J','u','n','i','t'};
    char[] actual = "Junit".toCharArray();

    assertArrayEquals(expected, actual);
}

6.3 assertAll method

As mentioned above, the assert method not only performs a check, but also writes a lot of information about comparable objects to the log.

Let's make a comparison:

Address address = unitUnderTest.methodUnderTest();
assertEquals("Washington", address.getCity());
assertEquals("Oracle Parkway", address.getStreet());
assertEquals("500", address.getNumber());

But if one of the parameters does not match, then the rest will not be checked. But I would like them to still occur and their results be recorded in the log. But at the same time, if at least one check failed, then the test still failed.

There is a special method for this - assertAll() . As the first argument, it takes a comment to be written to the log, and then any number of assert functions.

Here is how our example would be rewritten with it:

Address address = unitUnderTest.methodUnderTest();
assertAll("Complex address comparison script",
    () -> assertEquals("Washington", address.getCity()),
    () -> assertEquals("Oracle Parkway", address.getStreet()),
    () -> assertEquals("500", address.getNumber())
);

Then if the address is incorrect, something like this will be written to the log:

	Complex scenario comparison address (3 failures)
	expected: <Washington> but was: <Seattle>
    expected: <Oracle Parkway> but was: <Main Street>
    expected: <500> but was: <5772>

6.4 assertTimeout method

Remember the @Timeout annotation ? It allowed to control the execution time of the entire method. But sometimes it is useful to set restrictions on the execution of some part of the code inside the method. You can use assertTimeout() for this .

The time is passed as the first parameter, and the code (function) that must be executed within the specified time is passed as the second. Example:

@Test
public void whenAssertingTimeout() {
    assertTimeout(
  	ofSeconds(2),
  	() -> {
    	// pause for one second
    	Thread.sleep(1000);
  	}
	);
}

The Assert class has 12 variants of the assertTimeout() method . If you want to learn more about them, welcome to the official documentation .

6.5 assertThrows method

Very often there are situations when you need to make sure that in a certain situation the code throws the right exception: it detects an error and throws the right exception. This is a very common situation.

In this case, there is another useful assert method - this is assertThrows() . The general format of its call is:

assertThrows(exception , code)

Basically, it is very similar to the assertTimeout() method , only it checks that the specified code throws the right exception. Example:

@Test
void whenAssertingException() {
    Throwable exception = assertThrows(
  	IllegalArgumentException.class,
  	() -> {
      	throw new IllegalArgumentException("Exception message");
  	}
    );
    assertEquals("Exception message", exception.getMessage());
}