Contents

Lesser used JUnit assertions

Introduction

In this article, we look at what assertions JUnit offers out of the box that you can use in your tests. Most of us know the assertEquals that check if two values are equal. But JUnit offers more assertions that we can use like assertTimeout, assertThrows, assertDoesNotThrow, assertTimeoutPreemptively, and fail.

AssertNotSame

You can use assertNotSame for test cases where you want to check that two references don't point to the same objects.

In the following example, we create two objects and check that the two references don't point to the same object.

1
2
3
4
5
6
7
8
@Test
void assertNotSame(){
    Bike bike = new Bike();
    Bike secondBike = new Bike();

    Assertions.assertNotSame(bike, secondBike);

}

AssertSame

AssertSame is the opposite of assertNotSame. With assertSame, we can verify that two references point to the same object.

In the following example, we use the bike reference twice to check that it points to the same object.

1
2
3
4
5
6
7
@Test
void assertSame(){
    Bike bike = new Bike();

    Assertions.assertSame(bike, bike);

}

AssertTimeout

JUnit offers a built-in way to verify that a method completes within a given time. In the following example we check that Thread.sleep(50) completes within 100 milliseconds.

1
2
3
4
5
6
@Test
void assertTimeout(){
    Assertions.assertTimeout(Duration.ofMillis(100), () -> {
        Thread.sleep(50);
    });
}

Fail

We can use fail() to let the test fail at a certain point. Fail() could be handy if you want to let a test fail if it reaches a specified branch.

The following unit test will fail because we call the fail method inside it.

1
2
3
4
@Test
void failTheTest(){
    Assertions.fail();
}

AssertLinesMatch

With assertLinesMatch we can verify if the strings inside two Lists or streams are the same.

In the following example, we compare two lists with the same content.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@Test
void assertLinesMatch(){
    List<String> expectedStrings = new ArrayList<>();
    expectedStrings.add("test");
    expectedStrings.add("test2");

    List<String> actualStrings = new ArrayList<>();
    actualStrings.add("test");
    actualStrings.add("test2");

    Assertions.assertLinesMatch(expectedStrings,actualStrings);
}

Conclusion

This article looked at some assertions you may not often see in tests. You may not even use them often, but it's always good to know these methods exist.

Further reading

More about testing in Java:

Have a question or idea?

Thank you for reading my post. Have any questions about this topic or an idea for a new topic? Please reach out to me on Twitter or send me an email.

If you want to read more about Java when I write about it – you can follow me on Twitter.