Introduction to JUnit 4 in Java

1. What is JUnit?

JUnit is the most popular unit testing framework available for the Java programming language.  Originally written by Erich Gamma and Kent Beck.

It is of vital importance in test driven development which relies on very small development cycles of write some code, test the code, write some more code, test some more, etc.  The idea is that by doing this in small bursts the stability of the code and programmer productivity will be increased.   Using this methodology, the developers are encouraged to write the test first, which will initially be failing.  Then the developer will write the code to ensure that it passes the newly added test case.

JUnit Annotations

junit1JUnit 4.x uses the following annotations to configure what methods will be used for test cases. The following table give you general overview of the common annotations and their descriptions.

AnnotationDescription
@TestThis annotation identifies the method as a test method
@Test(timeout=300)This annotation will cause the test to fail if it exceeds the time specified in milliseconds
@Test(expected={exception.class})This annotation will succeed if the exception does occur
@Ignore(“Test is being ignored”)This annotation will ignore the method or class, depending on where this annotation is placed. It it typically used when the junit test case has not been modified to support the changes currently underway or the code has not yet been completed.
@BeforeThis annotation will cause the method to execute before every test. The @Before and @After annotations set up the environment and initialize the test cases before and after each run.
@AfterThis annotation will cause the method to execute after every test
@BeforeClassThis annotation specifies the method that will be executed only once before starting all the tests.
@AfterClassThis annotation specifies the method that will be executed only after finishing all the tests.

JUnit Assertions

In order to use the assertions in JUnit 4.x you will need to import the Assert class using the static import or use the full class name like Assert.assertTrue()…

AssertionDescription
assertEquals(String [message], boolean expected,
boolean actual)
Tests the two values are equal. This is an overloaded method
assertArrayEquals(int[], int[])Tests the two arrays are equal. This is an overloaded method to support all primative types and object
assertTrue(boolean cond)Ensures that the condition is true
assertFalse(boolean cond)Ensures that the condition is false
assertNull(Object obj)Checks that the object is null
assertNotNull(Object obj)Checks that the object is not null

What’s Next

Next we will Installation and set up so we can run our first tests.

Other Related Posts

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

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