JUnit test framework provides following important features
Fixtures
Test suites
Test runners
JUnit classes
Fixtures is a fixed state of a set of objects which can be used as a baseline for running tests.
A test fixture ensures that there is a fixed environment in which tests are run so that results are repeatable.
We can use the following two methods to setup a fixture.
setUp() method which runs before every test invocation.
tearDown() method which runs after every test method.
Let's check one example:
import junit.framework.*; public class JavaTest extends TestCase { protected int value1, value2; // assigning the values protected void setUp(){ value1=1; value2=1; } // test method to add two values public void testAdd(){ double result= value1 + value2; assertTrue(result == 2); } }
Test suite bundles unit tests cases and run it together.
In JUnit, both @RunWith and @Suite annotation are used to run the suite test.
Here is an example which uses TestJunit1 & TestJunit2 test classes.
import org.junit.runner.RunWith; import org.junit.runners.Suite; //JUnit Suite Test @RunWith(Suite.class) @Suite.SuiteClasses({ TestJunit1.class ,TestJunit2.class }) public class JunitTestSuite { }
Here is the code for TestJunit1.
import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit1 { @Test public void testPrintMessage() { assertEquals(1, 1+1); } }
Here is the code for TestJunit2.
import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit2 { @Test public void testSalutationMessage() { assertEquals(1, 1+0); } }
Test runner can execute the test cases.
import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class Main { public static void main(String[] args) { Result result = JUnitCore.runClasses(YourJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } }