Unit Test Tests Very Specific, Much Focused, Single Aspect of Functionality

Total Page:16

File Type:pdf, Size:1020Kb

Unit Test Tests Very Specific, Much Focused, Single Aspect of Functionality

Spring Testing

1. Unit Testing. “Unit Test” tests very specific, much focused, single aspect of functionality.

Specific: Independent of environment, other Unit test and test execute order. Focused: simulate and test in isolation. Determine whether it behaves exactly as we expect. Functional: High quality as the same as the production code . Easy to write code and fast to run.

Unit test in Dao layer: Model: package test.model.dao; //test package import org.springframework.context.ApplicationContext; //Spring Application import org.springframework.context.support.FileSystemXmlApplicationContext;

//input configuration xml file import iadvisezou.model.dao.AdviceDao; //AdviceDao need to be tested import iadvisezou.model.businessobject.Advice; //object import junit.framework.Assert; import junit.framework.TestCase;

//test AdviceDao public class AdviceDaoTest extends TestCase { private ApplicationContext ctx = null; private Advice record = null; private AdviceDao dao = null;

protected void setUp() throws Exception { //init super.setUp(); String[] paths = {"/applicationContext.xml"}; //set Spring configuration xml file ctx = new FileSystemXmlApplicationContext(paths); dao = (AdviceDao) ctx.getBean("adviceDao"); //get AdviceDao bean from

// ApplicationContext record = new Advice(); }

protected void tearDown() throws Exception { //the end super.tearDown(); dao = null; }

public void testGetAdvice() { //Test getAdvice record = dao.getAdvice(new Integer(1)); Assert.assertEquals(dao.getAdvice(new Integer(1)).getAdviseruserid(),"admin");

} public void testSaveAdvice() { //Test Save Advice record.setAdvice("just a junit test"); //set test value record.setAdviseruserid("admin"); record.setProblemId(new Integer(2)); dao.saveAdvice(record); //save current Advice Assert.assertNotNull(record.getAdviceId()); //AdviceId generator class = native // If save is success, then get a new AdviceId }

Create a TestSuite to test all the Dao Layer Unit Test. package test.model.dao; import junit.framework.Test; import junit.framework.TestSuite; public class DaoAllTests {

public static Test suite() { TestSuite suite = new TestSuite("Test for test.model.dao"); //$JUnit-BEGIN$ suite.addTestSuite(ProblemDaoTest.class); suite.addTestSuite(CustomerDaoTest.class); suite.addTestSuite(CategoryDaoTest.class); suite.addTestSuite(RankDaoTest.class); suite.addTestSuite(AdviceDaoTest.class); //$JUnit-END$ return suite; }

} Unit Test in Service layer: package test.model.service; import junit.framework.TestCase; import iadvisezou.model.service.CustomerService; import iadvisezou.model.service.impl.CustomerServiceImpl; import iadvisezou.model.businessobject.Account; import iadvisezou.model.dao.CustomerDao; import iadvisezou.model.exception.IadvisezouException; import junit.framework.Assert; import org.easymock.MockControl; public class CustomerServiceMockTest extends TestCase {

private Account record = null; private CustomerService service = new CustomerServiceImpl(); private MockControl control; private CustomerDao MockDAO;

protected void setUp() throws Exception { control = MockControl.createControl(CustomerDao.class); MockDAO = (CustomerDao) control.getMock(); service.setCustomerDao(MockDAO);

}

protected void tearDown() throws Exception { super.tearDown(); service = null; }

public void testSaveAccount() { try { record = new Account(); record.setUsername("test"); record.setFirstName("test"); record.setLastName("test"); record.setPassword("test"); record.setEmail("test@email"); record.setState("Texas"); record.setCountry("USA"); record.setRole("iadvise"); record.setCity("waco"); record.setAddress1("baylor"); record.setZip("76706"); record.setPhone("254-710-4518"); //set expected behavior on DAO MockDAO.saveAccount(record); control.setVoidCallable(); //switch from record to playback control.replay(); service.saveAccount(record); Assert.assertEquals(record.getFirstName(),"test"); control.verify();

} catch (IadvisezouException e) { e.printStackTrace(); } }

} Unit Test in Web layer:

Unit Test in Web layer only tests the Spring controller. In order to make sure that the application’s interfaces work correctly as we expected. We do not create the Spring application context, we use EasyMock library to generate the mock class and set their dependences. package test.view.controller; import icpc.service.ServiceLocator; import iadvisezou.model.service.CategoryService; import iadvisezou.view.controller.CategoryListController; import junit.framework.TestCase; import org.easymock.MockControl; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.web.servlet.ModelAndView; public class MockCategoryListControllerTest extends TestCase { private CategoryListController c; private MockHttpServletRequest request; private ModelAndView mv; MockControl serviceLocator; MockControl service; ServiceLocator serviceLocator;

protected void setUp() throws Exception { c = new CategoryListController(); control = MockControl.createControl(ServiceLocator.class); //create Mock class serviceLocator = (ServiceLocator)control.getMock(); c.setServiceLocator(serviceLocator);

serviceLocator.getService("categoryService"); //create Mock class service = MockControl.createControl(CategoryService.class);

CategoryService categoryService =(CategoryService)service.getMock();

control.setReturnValue(categoryService); }

protected void tearDown() throws Exception { super.tearDown(); }

public void testDisplayForm() throws Exception { control.replay(); //check to make sure CategoryListController get //parameters

request = new MockHttpServletRequest("GET","/categorys.html"); mv = c.handleRequest(request, new MockHttpServletResponse()); assertEquals(2,mv.getModel().size()); control.verify(); }

} 2. Integration Testing Integration Testing is a logical extension of unit testing and tests how the constructed components work together. We create the Spring application context and let the framework instantiate the beans. package test.view.controller; import iadvisezou.model.businessobject.Account; import iadvisezou.view.controller.CreateUserController; import junit.framework.TestCase; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.ModelAndView; public class CreateUserControllerTest extends TestCase { private XmlWebApplicationContext ctx; private CreateUserController c; private MockHttpServletRequest request; private ModelAndView mv; private Account account;

protected void setUp() throws Exception { String[] paths = {"applicationContext.xml", "iadvisezou-servlet.xml"}; ctx = new XmlWebApplicationContext(); ctx.setConfigLocations(paths); ctx.setServletContext(new MockServletContext("")); ctx.refresh(); c = (CreateUserController) ctx.getBean("createUserController"); account = new Account(); account.setUsername("test1"); account.setFirstName("FirstName"); account.setLastName("LastName");

}

protected void tearDown() throws Exception { super.tearDown(); }

public void testCreate() throws Exception { request = new MockHttpServletRequest("POST", "/createUser.html"); request.addParameter("username", account.getUsername()); request.addParameter("firstName", account.getFirstName()); request.addParameter("lastName", account.getLastName()); request.addParameter("password","test"); request.addParameter("email","[email protected]"); request.addParameter("city","waco"); request.addParameter("state","Tx"); request.addParameter("zip","76706"); request.addParameter("phone","254-214-4444"); request.addParameter("country","USA"); request.addParameter("save","");

mv = c.handleRequest(request, new MockHttpServletResponse());

String errorsKey = BindException.ERROR_KEY_PREFIX + c.getCommandName(); Errors errors = (Errors) mv.getModel().get(errorsKey); assertNull(errors); //check validation output }

}

Recommended publications