In this tutorial, we will quickly walk-through org. junit. Assert
class methods with examples.
Assert.assertTrue(..) and Assert.assertFalse(..)
These assert methods confirm that a condition is true or not.
public class AssertionExample { @Test public void test1() { String str = "test string"; Assert.assertTrue("str cannot be empty", str != null && str.length() != 0); Assert.assertFalse("str cannot by empty", str == null || str.length() == 0); } .............}
mvn -q test -Dtest=AssertionExample#test1
Output
d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test1-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.041 sec - in com.logicbig.example.AssertionExampleResults :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
In above example, we are running only one test method using maven 'test' command. Check out the related tutorial here.
All method in Assert class comes with two overloaded variants; one accepts an extra message parameter to show when assertion fails. Assert methods internally throw java. lang. Assertion Error
when the specified condition does not satisfy.
Let's write a test that fails:
public class AssertionExample { ............. @Test public void test2() { String str = null; Assert.assertTrue("str cannot be empty", str != null && str.length() != 0); } .............}
mvn -q test -Dtest=AssertionExample#test2
Output
d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test2-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.049 sec <<< FAILURE! - in com.logicbig.example.AssertionExample
test2(com.logicbig.example.AssertionExample) Time elapsed: 0.007 sec <<< FAILURE!
java.lang.AssertionError: str cannot be empty
at com.logicbig.example.AssertionExample.test2(AssertionExample.java:21)Results :
Failed tests:
AssertionExample.test2:21 str cannot be emptyTests run: 1, Failures: 1, Errors: 0, Skipped: 0
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project junit-assertions: There are test failures.
[ERROR]
[ERROR] Please refer to D:\example-projects\junit\junit-assertions\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
assertEquals(..)
These methods assert that two objects are equal by internally calling Object#equals(..)
method.
public class AssertionExample { ............. @Test public void test3() { Number a = new Integer(5); Assert.assertEquals("The number is not 5", a, 5); } .............}
mvn -q test -Dtest=AssertionExample#test3
Output
d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test3-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec - in com.logicbig.example.AssertionExampleResults :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
If both of the objects are null then test passes, if one of them is null then the test fails without throwing NullPointerException.
Other Overloaded variants of assertEquals(..)
There are overloaded variants of these methods which accepts primitives. This is to avoid autoboxing and hence making these method calls more efficient.
There's one more overloaded version of these methods for double comparision which provide an option to specify delta (acceptable positive/negative difference):
public static void assertEquals(String message, double expected, double actual, double delta)
public class AssertionExample { ............. @Test public void test4() { double d = 2.6; Assert.assertEquals("The numbers are not approximately equal", d, 3, 0.5); } .............}
mvn -q test -Dtest=AssertionExample#test4
Output
d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test4-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.049 sec - in com.logicbig.example.AssertionExampleResults :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
assertArrayEquals(..)
These overloaded methods internally use Arrays.deepEquals() for array comparision. Each elements are checked for being equal individually. Check out the difference between Arrays.equals, Arrays.deepEquals and equals.
public class AssertionExample { ............. @Test public void test5() { int[] integers = {3, 5, 7}; Assert.assertArrayEquals("The numbers are not equal", integers, new int[]{3, 5, 7}); } @Test public void test6() { Object[] integers = {3, 5, new int[]{7, 9}}; Assert.assertArrayEquals("The numbers are not equal", integers, new Object[]{3, 5, new int[]{7, 9}}); } .............}
mvn -q test "-Dtest=AssertionExample#test5, AssertionExample#test6"
Output
d:\example-projects\junit\junit-assertions>mvn -q test "-Dtest=AssertionExample#test5, AssertionExample#test6"-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.049 sec - in com.logicbig.example.AssertionExampleResults :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
There are overloaded versions of assertArrayEquals(..) which accepts primitives or Objects parameters.
assertSame(..) and assertNotSame(..)
These overloaded methods compare the objects based on '==' and not based on 'equals' method.
public class AssertionExample { ............. @Test public void test7() { String str1 = new String("test string"); String str2 = new String("test string"); Assert.assertSame("Same objects reference failed", str1, str1); Assert.assertNotSame("Different objects not same failed", str2, str1); Assert.assertSame("Different objects reference but have same value failed", str2, str1); } .............}
mvn -q test -Dtest=AssertionExample#test7
Output
d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test7-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.051 sec <<< FAILURE! - in com.logicbig.example.AssertionExample
test7(com.logicbig.example.AssertionExample) Time elapsed: 0.006 sec <<< FAILURE!
java.lang.AssertionError: Different objects reference but have same value failed expected same:<test string> was not:<test string>
at com.logicbig.example.AssertionExample.test7(AssertionExample.java:55)Results :
Failed tests:
AssertionExample.test7:55 Different objects reference but have same value failed expected same:<test string> was not:<test string>Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project junit-assertions: There are test failures.
[ERROR]
[ERROR] Please refer to D:\example-projects\junit\junit-assertions\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
In above output the last call of assertSame fails.
assertThat(..)
These methods satisfy the condition provided by a matcher object. Here's the signature of one of these methods:
public static <T> void assertThat(java.lang.String reason, T actual, org.hamcrest.Matcher<T> matcher)
Hamcrest is a third party library used by JUnit framework. Hamcrest provides a generic way to create expression to check conditions. The interface Matcher is given by:
public interface Matcher<T> extends SelfDescribing { boolean matches(Object var1); void describeMismatch(Object var1, Description var2); /** @deprecated */ @Deprecated void _dont_implement_Matcher___instead_extend_BaseMatcher_();}
We would probably want to extend BaseMatcher instead of implementing this interface. Here's an example which checks if the expected number is a multiple of 2 or not.
public class AssertionExample { ............. @Test public void test9() { int i = 22; Assert.assertThat(i, createMultipleOfTwoMatcher()); } private BaseMatcher<Integer> createMultipleOfTwoMatcher() { return new BaseMatcher<Integer>() { @Override public void describeTo(Description description) { description.appendText("Not a multiple of 2."); } @Override public boolean matches(Object item) { Integer integer = (Integer) item; return integer != null && integer % 2 == 0; } }; } .............}
mvn -q test -Dtest=AssertionExample#test9
Output
d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test9-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.051 sec - in com.logicbig.example.AssertionExampleResults :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
Following fails which uses an instance of the same matcher class:
public class AssertionExample { ............. @Test public void test10() { int i = 23; Assert.assertThat(i, createMultipleOfTwoMatcher()); } .............}
mvn -q test -Dtest=AssertionExample#test10
Output
d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test10-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.054 sec <<< FAILURE! - in com.logicbig.example.AssertionExample
test10(com.logicbig.example.AssertionExample) Time elapsed: 0.008 sec <<< FAILURE!
java.lang.AssertionError:Expected: Not a multiple of 2.
but: was <23>
at com.logicbig.example.AssertionExample.test10(AssertionExample.java:90)Results :
Failed tests:
AssertionExample.test10:90
Expected: Not a multiple of 2.
but: was <23>Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project junit-assertions: There are test failures.
[ERROR]
[ERROR] Please refer to D:\example-projects\junit\junit-assertions\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
org.hamcrest.CoreMatchers provides various out of the box implementations of Matcher (accessible via static methods) :
public class AssertionExample { ............. @Test public void test8() { int i = 22; Assert.assertThat("The number is not 22", i, CoreMatchers.is(22)); Assert.assertThat("The number is 23", i, CoreMatchers.not(23)); } .............}
mvn -q test -Dtest=AssertionExample#test8
Output
d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test8-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec - in com.logicbig.example.AssertionExampleResults :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
assertNull(..) and assetNotNull(..)
These methods assert that an object is null or not null respectively.
public class AssertionExample { ............. @Test public void test11() { String str = "test string"; String str2 = null; Assert.assertNotNull("The str is null.", str); Assert.assertNull("The str is not null.", str2); } .............}
mvn -q test -Dtest=AssertionExample#test11
Output
d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test11-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.041 sec - in com.logicbig.example.AssertionExampleResults :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
fail(..)
These methods are used to fail a test manually. We will probably want to do that if we want to test the condition ourselves:
public class AssertionExample { ............. @Test public void test12() { String str = null; if (str == null) { Assert.fail("The provided str is null"); } }}
mvn -q test -Dtest=AssertionExample#test12
Output
d:\example-projects\junit\junit-assertions>mvn -q test -Dtest=AssertionExample#test12-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.AssertionExample
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.05 sec <<< FAILURE! - in com.logicbig.example.AssertionExample
test12(com.logicbig.example.AssertionExample) Time elapsed: 0.006 sec <<< FAILURE!
java.lang.AssertionError: The provided str is null
at com.logicbig.example.AssertionExample.test12(AssertionExample.java:105)Results :
Failed tests:
AssertionExample.test12:105 The provided str is nullTests run: 1, Failures: 1, Errors: 0, Skipped: 0
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project junit-assertions: There are test failures.
[ERROR]
[ERROR] Please refer to D:\example-projects\junit\junit-assertions\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
Dependencies and Technologies Used:
- junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
- maven-surefire-plugin 2.19.1: Maven Surefire MOJO in maven-surefire-plugin.
- surefire-junit4 2.19.1: SureFire JUnit 4.0+ Runner.
- JDK 1.8
- Maven 3.3.9
FAQs
What is assert in JUnit testing? ›
Assertions are utility methods to support asserting conditions in tests. These methods are accessible through the Assert class in JUnit 4, and the Assertions class in JUnit 5. In order to increase the readability of the test and the assertions, it's recommended to statically import the respective class.
What is an example of assert? ›He asserted that there were spies in the government. She asserted her independence from her parents by getting her own apartment. The boss was reluctant to assert his authority over his employees.
How do you assert two objects are equal in JUnit? ›The assertSame() method tests if two object references point to the same object. The assertNotSame() method tests if two object references do not point to the same object. void assertArrayEquals(expectedArray, resultArray); The assertArrayEquals() method will test whether two arrays are equal to each other.
What is Assertequal () used to check JUnit? ›assertEquals. Asserts that two object arrays are equal. If they are not, an AssertionError is thrown with the given message. If expecteds and actuals are null , they are considered equal.
What does assert () do? ›The assert() function prints a diagnostic message to stderr and aborts the program if expression is false (zero). The diagnostic message has one of the following formats, depending on the language level used during the compilation: Assertion failed: expression, file filename, line line-number.
What are the two types of assert? ›Hard Assertions | Soft Assertions |
---|---|
Test Execution will be aborted if the assert condition is not met | Test execution will continue till the end of the test case even if the assert condition is not met |
These include Basic Assertion, Emphathic Assertion, Escalating Assertion and I-Language Assertion (4 Types of Assertion).
What is 1 example of basic assertion? ›Basic Assertion Simple expression of standing up for personal rights, beliefs, feelings or opinions. Example: When being interrupted, "Excuse me, I'd like to finish what I'm saying." Empathic Assertion Recognition of other person's situation or feelings followed by another statement standing up for speaker's rights.
What is basic assertion examples? ›A basic assertion is a straightforward statement that expresses a belief, feeling, opinion, or preference. For example: “I would like to finish this email before we have our conversation.” or “I would like you to wait until I have finished speaking.”
How to assert two lists in JUnit? ›Using JUnit
We can use the logic below to compare the equality of two lists using the assertTrue and assertFalse methods. In this first test, the size of both lists is compared before we check if the elements in both lists are the same. As both of these conditions return true, our test will pass.
How to assert two strings in JUnit? ›
String obj1="Junit"; String obj2="Junit"; assertEquals(obj1,obj2); Above assert statement will return true as obj1. equals(obj2) returns true.
Can I have multiple asserts in one test? ›It's still the same test case, though: Successfully cancelling a reservation. There's nothing wrong with multiple assertions in a single test. The above example illustrates the benefits. A single test case can have multiple outcomes that should all be verified.
How to use assert in java test? ›An assertion is made using the assert keyword. Its syntax is: assert condition; Here, condition is a boolean expression that we assume to be true when the program executes.
What is the difference between verify and assert in JUnit? ›Assert: If the assert condition is true then the program control will execute the next test step but if the condition is false, the execution will stop and further test step will not be executed. whereas, Verify: There won't be any halt in the test execution even though the verify condition is true or false.
What is the difference between assert equals and assert same? ›The explanation is here – assertEquals() uses equals() method to validate if the two objects are equal whereas assertSame() uses the operator == to validate if two objects are equal. Both of these approaches vary; hence the results are different as well.
What is assert () in Java? ›An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
What is assert used to check? ›The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError.
What is assert and types? ›Assertions verify that the state of the application is same to what we are expecting. Selenium Assertions can be of three types: “assert”, “verify”, and ” waitFor”. When an “assert” fails, the test is aborted. When a “verify” fails, the test will continue execution, logging the failure.