Designing JUnit Test Cases
Junit is a Java framework for performing unit tests on code. By testing code after every change, programmers can be reassured that changing a small amount of code does not break the larger system. Without automated testing tools like JUnit, retesting can be a tedious and inaccurate process. By allowing the testing process to occur frequently and automatically, you can keep software coding errors at a minimum.
• Creating test cases :
Test cases for JUnit are written as Java classes that extend the JUnit framework. These classes have a number of methods, each of which tests a particular function, or unit, of the code. Creating a new test case is easy.Writing a new test case requires creating a new Java class.
This class is called the PropertyManagerTest?.java, and it’s where you write your tests. Each time a test is called, JUnit will execute the setUp() method for you to initialize any values you need. Next, it will call a test case and then call tearDown() to undo the initialization and go on to the next test.
• Example
•
package com.sample;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class PropertyManagerTest {
PropertyManager pm=null;
public static void setUpBeforeClass() throws Exception {
}
public static void tearDownAfterClass() throws Exception {
}
public void setUp() throws Exception {
pm=new PropertyManager();
}
public void tearDown() throws Exception {
pm=null;
}
@Test
public final void testLoadProperties() {
try{
assertNotNull(“Unable to load Properties from External File”,pm.loadProperties());
assertTrue(“No properties from external file”,pm.loadProperties().size()>0);
}catch(Exception e){
fail(“Property File is not available or cannot be created”);
}
}
@Test
public final void testGetProperty() {
String propertyKey=”dashboard.targetenvironment”;
String propertyValue=”ec2″;
try{
assertNotNull(“Unable to load Properties from External File”,pm.loadProperties());
assertTrue(“No properties from external file”,pm.loadProperties().size()>0);
assertNotSame(“Given Property is not Available in properties file”,”",pm.getProperty(propertyKey));
assertEquals(“Improper Property Value”,propertyValue,pm.getProperty(propertyKey));
}catch(Exception e){
fail(“Property File is not available or cannot be created”);
}
}
}
}
The above class contains two tests :
• testLoadProperties()
1) Check the properties available or not in property file.
• testGetProperty()
1) Check the properties available or not in property file.
2) Check the given input property against property in property file.
3) Check the given input property value against property value in property file.
