Software QA FYI - SQAFYI

Unit Testing with JUnit

By:

JUnit unit test in version 4.x is a test framework which uses annotations to identify methods that specify a test. Typically these test methods are contained in a class which is only used for testing. It is typically called a Test class.

The following code shows a JUnit test method which can be created via File ? New ? JUnit ? JUnit Test case.

@Test
public void testMultiply() {

// MyClass is tested
MyClass tester = new MyClass();

// Check if multiply(10,5) returns 50
assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5));
}


JUnit assumes that all test methods can be executed in an arbitrary order. Therefore tests should not depend on other tests.

To write a test with JUnit you annotate a method with the @org.junit.Test annotation and use a method provided by JUnit to check the expected result of the code execution versus the actual result.

You can use the Eclipse user interface to run the test, via right-click on the test class and selecting Run ? Run As ? JUnit Test. Outside of Eclipse you can use org.junit.runner.JUnitCore class to run the test.
1.3. Available JUnit annotations

The following table gives an overview of the available annotations in JUnit 4.x.

1.4. Assert statements

JUnit provides static methods in the Assert class to test for certain conditions. These assertion methods typically start with asserts and allow you to specify the error message, the expected and the actual result. An assertion method compares the actual value returned by a test to the expected value, and throws an AssertionException if the comparison test fails.

The following table gives an overview of these methods. Parameters in [] brackets are optional.

1.5. Create a JUnit test suite

If you have several test classes you can combine them into a test suite. Running a test suite will execute all test classes in that suite.

The following example code shows a test suite which defines that two test classes should be executed. If you want to add another test class you can add it to @Suite.SuiteClasses statement.

Full article...


Other Resource

... to read more articles, visit http://sqa.fyicenter.com/art/

Unit Testing with JUnit