AdBlock Detected

It looks like you're using an ad-blocker!

Our team work realy hard to produce quality content on this website and we noticed you have ad-blocking enabled. Advertisements and advertising enable us to continue working and provide high-quality content.

Assertions JUnit5

In this article, we are going to see the different types of assertions in JUnit 5 with examples, that we can apply in our test phase in our applications.

What are assertions in JUnit 5?

Assertions are methods that allow us to assert the result of an operation. These methods are provided by the Assertions class in JUnit 5.

assertEquals(2, 2);

Assertions in JUnit 5

Assertions in JUnit 5 allow us to check all primitive types and are supported by the functionalities introduced in Java 8, so the assert output message can be a Supplier.

Let’s see the different types of asserts that we can find in JUnit 5.

assertNotEquals in JUnit 5

The assertNotEquals method allows us to verify that the expected value and the actual value are different.

@Test
void when_assert_two_values_then_assert_not_equals() {
    String hi = "hi"; 
    
    assertNotEquals("bye", hi, "Value is different than "bye");
}

assertEquals in JUnit 5

The assertEquals method works in the opposite way to assertNotEquals, i.e., it verifies that the expected value and the actual value are equal.

@Test
void when_assert_two_values_then_assert_are_equals() {
    String hi = "hi"; 
    
    assertEquals("hi", hi);
}

An important feature of assertEquals is that it allows us to add a Delta value that sets a difference between the expected and actual values.

@Test
void when_assert_2_times_pi_then_assert_has_delta() {
    Double pi = 3.14; 
    Double piDouble = pi*2;

    Double delta = 0.28;

    assertEquals(6, piDouble, delta);
}

assertArrayEquals with JUnit 5

assertArrayEquals allows us to verify if the expected array is equal to the actual array.

@Test
public void when_assert_two_arrays_then_are_equals() {
    
    char[] expected = "Pepito".toCharArray();
    
    char[] actual = { 'P', 'e', 'p', 'i', 't', 'o' };


    assertArrayEquals(expected, actual, "Pepito arrays are not equals");
}

assertTrue in JUnit 5

AssertTrue allows us to verify that a condition between the actual and expected values is true.

@Test
public void when_assert_two_values_then_are_equals() {
    
    int expected = 7;
    
    int actual = 5+2;

    assertTrue(expected, actual, "Values are equals");
}

As we have mentioned before, assert in JUnit 5 relies on lambda expressions, so the above assert can be indicated as follows:

@Test
public void when_assert_two_values_then_are_equals() {
    
    int expected = 7;
    
    int actual = 5+2;

    BooleanSupplier condition = () -> expected > actual;

    assertTrue(condition, "expected and actual are equals");
}

Using assertFalse

AssertFalse in JUnit 5 works in the opposite way to assertTrue, i.e., it ensures that two values (expected and actual) are different.

@Test
public void when_assert_two_values_then_are_equals() {
    
    int expected = 77;
    
    int actual = 5+2;

    assertFalse(expected, actual, "Values are not equals");
}

assertNotNull in JUnit 5

assertNotNull allows us to ensure that the actual value is different from null.

@Test
void when_assert_not_null_then_not_null_value() {
    String sayHi = "hi";

    assertNotNull(sayHi, () -> "Value cannot be null");
}

assertNull

assertNull in JUnit 5 is used to ensure that the value we want to verify is null.

@Test
void when_assert_null_then_null_value() {
    String sayHi = null;

    assertNotNull(sayHi, () -> "Value must be null");
}

assertSame in Junit 5

AssertSame is used to reference that two objects refer to the same object. Let’s see it better with an example:

    @Test
    public void given_two_string_when_assert_same_then_assert_is_true(){
    	
        String cityA ="Spain";
    	String cityAA ="Spain";
    	Assertions.assertSame(cityA,cityAA);
    }
    
    @Test
    public void given_two_string_when_assert_same_then_assert_is_false(){
    	
        String cityA ="Spain";
    	String cityAA ="Spain";
    	Assertions.assertSame(cityA,cityAA, "cityA and cityAA do not refer to same object"););
    }

assertNotSame

AssertNotSame is one of the assert types in JUnit 5 that allows us to ensure that two objects refer to different objects. It works the same as assertSame, but in reverse.

    @Test
    public void given_two_string_when_assert_not_same_then_assert_is_true(){
    	
        String cityA ="Spain";
    	String cityAA ="France";
    	Assertions.assertNotSame(cityA,cityAA);
    }

assertAll

JUnit 5 introduced a feature called AssertAll that allows us to group assertions together.

@Test
void given_multiples_number_when_assert_all_then_every_assert_is_ok() {
    int value = 5;
    assertAll(
      "heading",
      () -> assertEquals(10, 5+5),
      () -> assertEquals(5, value),
      () -> assertNotNull(value)
    );
}

assertIterableEquals in JUnit 5

AssertIterableEquals functions in the same way as AssertArrayEquals, but it is focused on the Iterable object.

assertLinesMatch

It asserts if two lists of String are equal, distinguishing from assertEquals and assertIterableEquals in:

  • Checks expected.equals(actual).
  • Uses the String.matches() method to treat the line as a regular expression.
  • Check if the expected line is a fast-forward marker. If so, apply the fast-forward and repeat from step 1.

A fast-forward marker is a string that starts and ends with >> and has at least four characters. The program discards any characters between the literals.

	@Test
	void given_values_to_compare_when_assert_lines_match_then_true() {

		List<String> expected = asList("Blue", "\\w+", "Sun");

		List<String> actual = asList("Blue", "hola", "Sun");

		assertLinesMatch(expected, actual);
	}

In the previous example, we pass a regular expression that accepts any word, so when comparing \w+ with “hola”, the result is true.

assertThrows

It allows us to validate if with a certain value our code will throw some exception.

	@Test
	public void given_wrong_values_when_parse_to_int_then_throw_exception() {

		Exception exception = assertThrows(ArithmeticException.class, () -> {
			int value = 5/0;
		});

		String expectedMessage = "/ by zero";
		String actualMessage = exception.getMessage();

		assertTrue(actualMessage.contains(expectedMessage));
	}

Example of assertTimeout in JUnit 5

The assertTimeout assertion type in JUnit 5 allows us to verify if our code will give some type of timeout in a certain time.

	@Test
	void given_1_second_of_time_out_when_request_process_then_return_true() {
		assertTimeout(ofSeconds(1),
				() -> {
					Thread.sleep(100);
				}
		);
	}

 assertTimeoutPreemptively in JUnit 5

The only difference between assertTimeoutPreemptively and assertTimeout is that if assertTimeoutPreemptively exceeds a timeout, the execution of the Executable or ThrowingSupllier is canceled.

	@Test
	void given_1_second_of_time_out_preemptively_when_request_process_then_return_true() {
		assertTimeoutPreemptively(ofSeconds(1),
				() -> {
					Thread.sleep(100);
				}
		);
	}

By applying this assertion we achieve that the executable is not further executed.

Conclusion of assertion types in JUnit 5

In this entry, we have seen the different types of assertions in JUnit 5 with examples, which will help us in our tests.

If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!

Leave a Reply

Your email address will not be published. Required fields are marked *