JUnit Adam Heath
What is JUnit? JUnit is a unit testing framework for the Java programming language It allows developers to swiftly and easily test parts of Java applications It is part of the xUnit family of tools first designed by Kent Beck for the Smalltalk programming language
Unit Testing Used for “Bottom Up” testing Test “units” of code Class → Test Class Orderless Tests written early Can be automated Ran often
JUnit Assertions All asserts have an optional first argument 'message' which would be output on failure assertArrayEquals(x, y) assertEquals(x, y) assertFalse(boolean) assertTrue(boolean) fail() assertNull(object) assertNotNull(object) assertSame(object) assertNotSame(object) assertThat(x, Matcher)
JUnit Testing public class Maths { private int[] arr; private int count, total; // constructor, initiate to zero public Maths(); //Divide two numbers public static double divide(int a, int b); //Add integers to sum public void addtosum(int a); //Get the average public double average(); //Get the array storing our integers public int[] getArr(); }//end class Maths
JUnit Testing import org.junit.* ; public class MathsTest public void test_divide() { assertEquals(Maths.divide(4,2), 2.0) ; assertEquals(Maths.divide(2,4), 0.5) ; public void test_divideZero() { Maths.divide(4,0); public void test_addtosum() { Maths m = new Maths(); m.addtosum(4); int[] expected = { 4 }; assertArrayEquals(expected, m.getArr()) m = null; }
JUnit public void test_addtosumMore() { Maths m = new Maths(); m.addtosum(9878); m.addtosum(0); int[] expected = { 9878, 0 }; assertArrayEquals(expected, m.getArr()) m = null; public void test_average() { Maths m = new Maths(); m.addtosum(5); m.addtosum(8); m.addtosum(23); m.addtosum(1); assertEquals(m.average(), 9.25) ; m = null; } }//class
JUnit public void beginMaths() { Maths m = new Maths(); public void endMaths() { m = null; } Fixtures allow us to define methods to be run before and after every test in that class We can also annotations
JUnit public void beginMaths() { Maths m = new Maths(); public void endMaths() { m = null; public void test_addtosum() { m.addtosum(4); int[] expected = { 4 }; assertArrayEquals(expected, m.getArr()) } This test would run: beginMaths() test_addtosum() endMaths()
Running JUnit Junit should be added to Java CLASSPATH Text interface java org.junit.runner.JUnitCore MathsTest GUIs are available Integrated into IDE
Advantages Fast Early discovery of errors Bug fixing Regression testing Time saved in testing Can help with design Can help to document the system
Disadvantages Developer overhead Does not deal with Integration or Customer testing Tests must be kept up to date Must be ran often
Questions?