Index


Overview


JUnit is a unit testing framework derived from the xUnit (which comes from Smalltalk's SUnit).

JUnit is a way to code unit tests, to test our code.

Without IDE


This example demonstrates using JUnit end-to-end (from download to test execution). This example does not depend on an IDE.
Note that some IDE's may have JUnit pre-installed.


Another Example

For more info on JUnit, go here.

For instructions on how to just download JUnit, see below.

With IDE


Some of the more sophisticated IDE's provide a menu-driven wizard to add JUnit tests.

For example, with Eclipse you can do the following:


Example JUnit Test and Assert


  • "@Test" tells Junit that this method is a test method
  • assertEquals is just one of the large set of assert methods that are available in JUnit

Also see: assert
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class PointTest {

	
1
@Test void test1() { Point p = new Point(1000, 500);
2
assertEquals(p.getX(), 1000, "x"); } @Test void test2() { Point p = new Point(1000, 500); assertEquals(p.getY(), 500, "y"); } }

Downloading JUnit


If you have already downloaded JUnit, skip this section.


Versions


JUnit 5

	org.junit.jupiter.api

	import static org.junit.jupiter.api.assertTrue;
	import static org.junit.BeforeEach
	etc
	
JUnit <= 4

	import static org.junit.Assert.assertTrue;
	import static org.junit.Before
	etc


Customization



   System.out.println(testInfo.getDisplayName());
    System.out.println(testInfo.getTags());
    System.out.println(testInfo.getTestClass());
    System.out.println(testInfo.getTestMethod());

    @BeforeEach
    void init(TestInfo testInfo) {
    	println(testInfo.getDisplayName());
    }
    @Test
    @DisplayName("Test Edge Case -- Empty List")
     public void testEdgeCaseEmptyList {
	//...
     {

    @AfterEach
    void tearDown(TestInfo testInfo) {
    	println(testInfo.getDisplayName());
    }


	/*public static void assertTrue(boolean b){
	     try{
	          Assert.assertTrue(b);
	          System.out.println("PASSED");
	     }catch(AssertionError e){
	          System.out.println("FAILED");
	        throw e;
	     }
	}*/


In Eclipse


Easiest way in eclipse to have a project hooked up to JUnit is do a "New" and add a Junit Test Case, that will pull in the library (if needed). Then you can delete the test case (or use it).


Breaking On Failures



To break on failures (open debugger) --

Add breakpoint on Assert.
e.g. in Eclipse this is in Debug Window on "Breakpoints" tab via "J!" button.
Add exceptions for e.g.
AssertionError
AssertionFailedError

This is also helpful for Java general exceptions:
RuntimeException


NOTE WELL: Remember to include (check on in Eclipse):

"Subclasses of this exception"

References