JUnit
JUnit is a simple, open source framework to write and run repeatable tests.
Installing JUnit
1. Download the latest version of JUnit, from junit.org.
2. Then install JUnit on your platform:
Windows
1.Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.
2. Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar
Unix (bash)
1.Unzip the junit.zip distribution file to a directory referred to as $JUNIT_HOME.
2.Add JUnit to the classpath:
export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit.jar
Writing Test:
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):
@Test
public void testMethod() {
3. That asserts expected results on the object under test
assertTrue(...);
4. Use fail for unexpected behavior.
try {
...
} catch (Exception e) {
fail (...);
}
}
}
Best practices:
1. Start method name with the word ‘test’.
2. Use a describing method name.
3. Test each method in an independent testing method.
4. Test can’t be dependent on each other.
5. Keep the testing classes in the same package than the tested class.