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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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: