jUnitIn eclipse, create a
source folder to store content of testing classes. Name it "test". In
project properties go to Build Path, Add Library, jUint Make a new jUnit Test Case, jUnit 4, @Before Any method annotated, will be executed before performing any of the test methods. //to allocate resources @After Any method annotated, will be executed after performing any of the test methods. //to release resources @Test Any method annotated, will be executed as a test case. @Ignore Test will be ignored @BeforeClass for all tests @AfterClass for all tests import static org.junit.Assert.*; import org.junit.Test; public class TestHelloWorldPrompt { @Test public void testX(){ HelloWorld h = new HelloWorld(); assertEquals("my message a", "Hello World", h.say()); } } if you
have a method that is meant to output to a file, don't pass in a
filename, or even a FileWriter . Instead, pass in
a Writer . That way you can pass in
a StringWriter to capture the output for testing
purposes. Then you can add a method
(e.g. writeToFileNamed(String filename) ) to
encapsulate the FileWriter creation.Test Constructors (when there are multiple) @Test public void testCreate() { assertEquals(23, new MyClass(23).getX()); } @Test(expected = IndexOutOfBoundsException.class) public void arraySizeTest() { ArrayList arr = new ArrayList(); arr.get(0); } To test private methods, you can use reflection to
subvert the access control mechanism with the aid of
the PrivilegedAccessor.
For details on how to use it,
read this
article. jUnit executes each test within a separate instance of the test class. It reports failure on each test. You can add a @BeforeClass annotation to a method
to be run before all the tests in a class, and
a @AfterClass annotation to a method to be run
after all the tests in a class. Access Private Fields. methods, constructors
PrivateAccessor to check the value of private fields in unit testing.
Handle Hard-to-Control Sources for Testing
|