Table of Contents
Java - Junit - How do I write and run a simple test?
About
Steps on how to write a sample junit test.
Articles Related
Steps
The source
Write a SimpleTest.java file
// 1- Create a class: import org.junit.*; import static org.junit.Assert.*; import java.util.*; public class SimpleTest { // 2 - Write a test method (annotated with @Test) that asserts expected results on the object under test: @Test public void testEmptyCollection() { Collection collection = new ArrayList(); assertTrue(collection.isEmpty()); } // 3 - If you are running your JUnit 4 tests with a JUnit 3.x runner, write a suite() method that uses the // JUnit4TestAdapter class to create a suite containing all of your test methods: public static junit.framework.Test suite() { return new junit.framework.JUnit4TestAdapter(SimpleTest.class); } // 4 - Although writing a main() method to run the test is much less important with the advent of IDE runners, // it's still possible: public static void main(String args[]) { org.junit.runner.JUnitCore.main("SimpleTest"); } }
Compilation
Download the Junit jar file and add it to the CLASSPATH.
set CLASSPATH=%CLASSPATH%;C:\temp\class\junit-4.8.1.jar javac SimpleTest.java
Run the test
- from the console:
java org.junit.runner.JUnitCore SimpleTest JUnit version 4.8.1 . Time: 0,006 OK (1 test)
- with the test runner used in main(), type:
java SimpleTest JUnit version 4.8.1 . Time: 0,007 OK (1 test)