Now you can create your test files. These should be created in the test packages package folder to keep them separate from the actual project code.
package yourprojects.somepackage;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class ExampleTest {
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class ExampleTest {
// Create objects needed to perform the test i.e. mock objects
private static ObjectToTest testObject;
@BeforeClass
public static void setUpClass() throws ConnectionException, SQLException {
testObject = new ObjectToTest(); // Initialise object to test
}
@AfterClass
public static void tearDownClass() throws Exception {
// Any connections made (e.g. such as database) should be closed here
}
@Test
public void testSomeMethod() throws ForumException {
assertTrue(testObject.someMethod());
private static ObjectToTest testObject;
@BeforeClass
public static void setUpClass() throws ConnectionException, SQLException {
testObject = new ObjectToTest(); // Initialise object to test
}
@AfterClass
public static void tearDownClass() throws Exception {
// Any connections made (e.g. such as database) should be closed here
}
@Test
public void testSomeMethod() throws ForumException {
assertTrue(testObject.someMethod());
assertIsEmpty(testObject.someMethod());
assertNotNull(testObject.someMethod());
assertEquals(true, testObject.someMethod());
assertSame(new ObjectToTest(), testObject.someMethod());
}
}
How it works
This class is testing a method (someMethod) in an object (ObjectToTest).
We start off by including all the JUnit libraries we need for the tests.
We then override the setUpClass and tearDownClass methods which organise the test environment for us. In the set up class we initialise the mock objects we need to test. In the tear down class method we close any connections we made during the testing.
Then we write the tests; I typically write one test for each result I expect e.g. testAMethodWithNullArguement(). Keeping the test methods separate makes it clearer what has failed.
The test method in the above example lists many of the more common assert methods I use depending on what kind of output I am expecting from the method being tested.
No comments:
Post a Comment