JUnit - a JavaBased Unit Testing Framework (JUnit 5 doc, AND JUnit 4)
-
Java based unit testing framework can use with any IDE.
- http://junit.org/
- junit.jar - package for JUnit
- IntelliJ AND JUnit --MUST READ
- AndroidStudio AND JUnit-- MUST READ
IDEs and JUnit The STEPS --note different IDEs may support different versions of JUnit (read documentation for youir IDE version)
We will highlight the use of JUnit inside of Eclipse. https://www.jetbrains.com/help/idea/create-tests.html
- Create a Project and make sure you add JUnit library to it in the Eclipse IDE
- Create some (at least basic) Project Class(es) Create some basic project class code ---it doesnt have to be complete but, at a beginning state with at least one methods(maybe that initally do nothing) and some class variables. You can start unit testing on this basic code and add more code to it doing unit testing right away.
- Include as necessary any packages/jar files necessary ---this an depend on IDE read requirements on IDE website
- example for IntelliJ for Junit5
- example for InteliJ for Junit 4 (in build.gradle file)
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
}
- For Each Class Create a TestCase class
- IntelliJ creating a Test Class OR AndroidStudio and Test Class
- Simple Example Class -AddressEntry, AND AddressEntryTest class
- creates your DogTest class, possibly with some boilerplate in it.
Below IntelliJ select class name and hit ALT-ENTER then Create test --- YOU need to follow your current IDEs instructions ---but will be similar
5. For Each TestCase class - fill in the code for the logic for each test case method (see Process below)
JUnit Testing Code Development Process
- JUnit (since version 4) uses annotations --
- For every method in the Dog (project code class), write a method in DogTest called testMethodName().
- (JUnit simply looks for methods beginning with lowercase "test", and figures they must be test methods.)
- For example, if the class being tested has a foo() method, then we might write a testFoo() method that calls foo() 5 different ways to see that it returns the right thing.
- ALSO, you can create other methods in the TestClass (i.e. DogTest) that may execute a number of methods --testing some kind of use case related to the class (i.e. Dog)
- (JUnit simply looks for methods beginning with lowercase "test", and figures they must be test methods.)
- METHODS from JUnit TestCase class to help with testing "assertions:
- assertsXXXX methods - come with JUnit to help test if results are what you expect.
- assertsEqual, assertsTrue, and more!!!
- assertEquals( desired-result, method-call );
- Works for primitives, and uses .equals() for objects - assertTrue( expr-that-should-be-true );
- assertEquals( desired-result, method-call );
- This is a list of the different types of assertion statements that are used to test your code. Any Java data type or object can be used in the statement. These assertions are taken from the JUnit API.
- assertEquals(expected, actual)
- assertEquals(message, expected, actual)
- assertEquals(expected, actual, delta) - used on doubles or floats, where delta is the difference in precision
- assertEquals(message, expected, actual, delta) - used on doubles or floats, where delta is the difference in precision
- assertFalse(condition)
- assertFalse(message, condition)
- assertNotNull(object)
- assertNotNull(message, object)
- assertNotSame(expected, actual)
- assertNotSame(message, expected, actual)
- assertNull(object)
- assertNull(message, object)
- assertSame(expected, actual)
- assertSame(message, expected, actual)
- assertTrue(condition)
- assertTrue(message, condition)
- fail()
- fail(message)
- failNotEquals(message, expected, actual)
- failNotSame(message, expected, actual)
- failSame(message)
- use these in your testMethodName() methods to compare results.
JUnit Annotations --some
@Test public void method() | Annotation @Test identifies that this method is a test method. |
@Before public void method() | Will perform the method() before each test. This method can prepare the test environment, e.g. read input data, initialize the class) |
@After public void method() | Test method must start with test |
@BeforeClass public void method() | Will perform the method before the start of all tests. This can be used to perform time intensive activities for example be used to connect to a database |
@AfterClass public void method() | Will perform the method after all tests have finished. This can be used to perform clean-up activities for example be used to disconnect to a database |
@Ignore | Will ignore the test method, e.g. useful if the underlying code has been changed and the test has not yet been adapted or if the runtime of this test is just to long to be included. |
@Test(expected=IllegalArgumentException.class) | Tests if the method throws the named exception |
@Test(timeout=100) | Fails if the method takes longer then 100 milliseconds |
Running JUnit
- Select the test class (i.e. DogTest), SEE YOUR IDEs documentation ; example ---right click, select Run JUnit Test OR RunAs -> JUnit Test Case
- Click on the JUnit tab in the left pane to see the results
OR
- click on the package on the left. Then running JUnit Tests will run all of the tests.
Example Running a set of methods in a TestCase clas called DogTest (see code below in Example 2)
Understanding when a JUnit test has "failed"
- double click a line in the "failures" list to go to the test method that failed.
- The stack trace at the lower left shows the call sequence. If there was an assert failure, it shows the expected and actual values. Double click it to get details of the expected and actual values.
- The data and variables are not live -- the JUnit report is of what happened in the past
- To see the data live, put a breakpoint in the work code, and select Debug... to run the unit test in the debugger where you can look at the values as it runs.
Here we introduce a failure in our testing method to cause it to fail (use fail method from TestCase class)
Example 1
Dog Class - project code
/** * */
/** * @author grewe * */ public class Dog { /** * represents dog's name */ String Name; /** * represents dog's breed */ String Breed; /** * represents age */ float Age;
/** * constructor sets Name, breed, age */ Dog(String n, String b, float a){ super(); this.Name = n; this.Breed = b; this.Age = a; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Dog d = new Dog("Jack", "pug", (float)3.0); System.out.println("Dog is " + d.getInfo());
} /** * @return Name */ String getName() { return this.Name; } /** * @param Name */ void setName(String n){ this.Name = n; }
/** * @return Breed */ String getBreed() { return this.Breed; } /** * @return Dog's info */ String getInfo(){ String s = "Name: " + this.Name + " \nBreed: " + this.Breed + " \nAge: " + this.Age; return s; } }
DogTest - TestCase class - WITH JUnit
Currently ONLY created the method testDog , need to complete the other methods i.e. testGetName to test the Dog's getName mehtod!!!!
import static org.junit.Assert.*;
import org.junit.Test;
/** * */
/** * @author grewe * */ public class DogTest4 {
/** * Test method for {@link Dog#Dog(java.lang.String, java.lang.String, float)}. */ @Test public void testDog() { Dog d = new Dog("Fido","jack russel", (float)5.0); String s = d.getInfo(); System.out.println("Test Case Results!!!\n\n" + s); assertEquals("Fido",d.getName()); //fail("Not yet implemented"); }
/** * Test method for {@link Dog#main(java.lang.String[])}. */ @Test public void testMain() { fail("Not yet implemented"); }
/** * Test method for {@link Dog#getName()}. */ @Test public void testGetName() { fail("Not yet implemented"); }
/** * Test method for {@link Dog#setName(java.lang.String)}. */ @Test public void testSetName() { fail("Not yet implemented"); }
/** * Test method for {@link Dog#getBreed()}. */ @Test public void testGetBreed() { fail("Not yet implemented"); }
/** * Test method for {@link Dog#getInfo()}. */ @Test public void testGetInfo() { fail("Not yet implemented"); }
}