How to Use Assertions
Item 12: JUnit: Unit Testing Made Simple
67: public static Test suite() {
68: TestSuite suite= new TestSuite(“Employee Form Unit Tests”);
69: suite.addTestSuite(employeeFormBeanTestCase.class);
70: return suite;
71: } 73: }
Listing 12.2 (continued)
Listing 12.3 illustrates how a test case should be written to test the JavaBean that was created. Notice the assert statements that check the getter/setter methods in the employ- eeFormBean component. These asserts ensure that expected behavior is maintained in our code and that bugs that might be introduced to this application are captured and resolved easily. One thing to be aware of when you do create unit tests with JUnit is that if you insert System.out.println()statements in your test cases, it does not print the text output to the console when you run your test from the command line.
01: import junit.framework.TestCase; 02:
03: public class employeeFormBeanTestCase extends TestCase { 04: public employeeFormBeanTestCase(String name) {
05: super(name); 06: }
07: public void noTestCase() { 08: }
09: public void testCase1() {
10: employeeFormBean eForm = new employeeFormBean(); 11: assertTrue(eForm != null);
12: }
13: public void testCase2() {
14: employeeFormBean eForm = new employeeFormBean(); 15: assertTrue(eForm != null);
16:
17: eForm.setFirstName(“Steven”);
18: assertTrue(“Steven” == eForm.getFirstName()); 19: }
20: public void testCase3() {
21: employeeFormBean eForm = new employeeFormBean(); 22: assertTrue(eForm != null);
23:
24: eForm.setLastName(“Fitzgerald”);
25: assertTrue(“Fitzgerald” == eForm.getLastName()); 26: }
27: public void testCase4() {
28: employeeFormBean eForm = new employeeFormBean(); 29: assertTrue(eForm != null); 30: 31: eForm.setFirstName(“John”); 32: eForm.setLastName(“Walsh”); 33: assertTrue(eForm.validate()); 34: }
35: public void testCase5() {
36: employeeFormBean eForm = new employeeFormBean(); 37: assertTrue(eForm != null);
38:
39: String s = eForm.getErrorMsg(“firstName”);
40: assertTrue(!s.equals(“Please enter your first name”)); 41: }
42: public void testCase6() {
43: employeeFormBean eForm = new employeeFormBean(); 44: assertTrue(eForm != null);
45:
46: String s = eForm.getErrorMsg(“lastName”);
47: assertTrue(!s.equals(“Please enter your last name”)); 48: }
49: public void testCase(int arg) { 50: }
51: }
Additionally, unit tests can be created to ensure that data in a database remains con- sistent and has not been corrupted during testing and integration operations. This is accomplished by creating unit tests that validate JDBC connections and user queries on database data. 01: 02: import java.sql.*; 03: import java.util.*; 04: import junit.framework.*; 05: import junit.runner.BaseTestRunner; 06:
07: public class dbQueryBean { 08:
09: private static final String DRIVER_NAME=”org.gjt.mm.mysql.Driver”; 10: private static final String DB_URL=”jdbc:mysql://localhost/States”; 11: private static final String USERNAME=””;
12: private static final String PASSWORD=””;
13: private static final String QUERY=”Select * from Topics”; 14:
15: Connection conn = null; 16: Statement stmt = null; 17: ResultSet rslt = null; 18: 19: public dbQueryBean() { 20: 21: try { 22: // get driver 23: Class.forName(DRIVER_NAME); 24: // connect to the MySQL db
25: Connection conn = Æ DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
26: Statement stmt = conn.createStatement(); 27: ResultSet rslt = stmt.executeQuery(QUERY); 28: } 29: catch(Exception e) { 30: } 31: } 32:
33: public void closeDb() 34: { 35: try { 36: // get driver 37: this.conn.close(); 38: } 39: catch(Exception e) { 40: } 41: } 42: Listing 12.4 dbQueryBean.java
43: public ResultSet getResultSet() { 44: return this.rslt;
45: } 46:
47: public Connection getConnection() { 48: return this.conn;
49: } 50:
51: public Statement getStatement() { 52: return this.stmt;
53: } 54:
55: /* main */
56: public static void main(String[] args) { 57: junit.textui.TestRunner.run(suite()); 58: }
59: 60: /**
61: * TestSuite that runs all the sample tests 62: *
63: */
64: public static Test suite() {
65: TestSuite suite= new TestSuite(“DB Query Unit Tests”); 66: suite.addTestSuite(dbQueryBeanTestCase.class);
67: return suite; 68: }
70: }
Listing 12.4 (continued)
The dbQueryBeanTestCase in Listing 12.5 demonstrates how to assess database con- nections and result sets that are returned from database queries. In most cases, a sim- ple instantiation of your bean followed by an assert after the invocation of your bean’s methods is the way to unit test your code. In this example, static database information is tested; on many enterprise systems the data is dynamic and tests like this would not be proper.
01: import java.sql.*;
02: import junit.framework.TestCase; 03:
04: public class dbQueryBeanTestCase extends TestCase { 05: public dbQueryBeanTestCase(String name) {
06: super(name); 07: }
08: public void noTestCase() { 09: }
10: public void testCase1() {
11: employeeFormBean eForm = new employeeFormBean(); 12: assertTrue(eForm != null);
13: }
14: public void testCase2() { 15:
16: try { 17:
18: dbQueryBean db = new dbQueryBean(); 19: assertTrue(db != null); 20:
21: // Get the resultset meta-data 22: ResultSet rslt = db.getResultSet();
23: ResultSetMetaData rmeta = rslt.getMetaData(); 24:
25: // Use meta-data to determine column #’s in each row 26: int numColumns = rmeta.getColumnCount();
27: String[] s = new String[numColumns]; 28:
29: for (int i=1; i < numColumns; i++) { 30: s[i] = rmeta.getColumnName(i); 31: }
32:
33: // check to see if db columns are correct 34: assertTrue(s[1].equals(“State”)); 35: assertTrue(s[2].equals(“AutomobileDealers”)); 36: assertTrue(s[3].equals(“BikeTrails”)); 37: assertTrue(s[4].equals(“Gyms”)); 38: assertTrue(s[5].equals(“Hospitals”)); 39: assertTrue(s[6].equals(“Laundromats”)); 40: assertTrue(s[7].equals(“Parks”)); 41: assertTrue(s[8].equals(“Physicians”)); 42: assertTrue(s[9].equals(“PetStores”)); 43: assertTrue(s[10].equals(“Restaurants”)); 44: assertTrue(s[11].equals(“RestAreas”)); 45: } 46: catch(Exception e) {} 47: }
48: public void testCase3() { 49:
50: try { 51:
52: dbQueryBean db = new dbQueryBean(); 53: assertTrue(db != null); 54:
55: // Get the resultset meta-data
56: ResultSet rslt = db.getResultSet();
57: ResultSetMetaData rmeta = rslt.getMetaData(); 58:
59: // Use meta-data to determine column #’s in each row 60: int numColumns = rmeta.getColumnCount();
61: String[] s = new String[numColumns]; 62:
63: for (int i=1; i < numColumns; i++) { 64: s[i] = rmeta.getColumnName(i); 65: }
66:
67: while (rslt.next()) {
68: for (int i=1; i < numColumns; ++i) {
69: if (rslt.getString(i).trim().equals(“Alabama”)) { 70: assertEquals(rslt.getString(i).trim(), Æ “Alabama”); 71: assertEquals(rslt.getString(i+1).trim(), Æ “KIA”); 72: assertEquals(rslt.getString(i+2).trim(), Æ “Bama Path”); 73: assertEquals(rslt.getString(i+3).trim(), Æ “Mr. Muscles”); 74: assertEquals(rslt.getString(i+4).trim(), Æ “St. Lukes”); 75: assertEquals(rslt.getString(i+5).trim(), Æ “Mr. Clean”); 76: assertEquals(rslt.getString(i+6).trim(), Æ “Tuscaloosa”); 77: assertEquals(rslt.getString(i+7).trim(), Æ “Dr. Nick”); 78: assertEquals(rslt.getString(i+8).trim(), Æ “Mr. Pickles”); 79: assertEquals(rslt.getString(i+9).trim(), Æ “Joes Pizzaria”); 80: assertEquals(rslt.getString(i+10).trim(), Æ “Selma”); 81: assertEquals(rslt.getString(i+11).trim(), Æ “Mr. Goodshoes”); 82: break; 83: } 84: } 85: } 87: } 88: catch(Exception e) {} 89: }
90: public void testCase(int arg) { 91: }
92: }
JUnit allows developers and testers to assess module interfaces to ensure that infor- mation flows properly in their applications. Local data structures can be examined to verify that data stored temporarily maintains its integrity, boundaries can be checked for logic constraints, and error handling tests can be developed to ensure that potential errors are captured. All developers should implement the JUnit framework to test their software components and to make certain that development teams don’t accept incon- sistencies in their programs.