1.0 Other languages |
||||
5.3 J2EE unit test without server in VelocityWeb |
||||
|
In VelocityWeb, you can write J2EE unit test without starting J2EE server. This can make the developing progress faster than before. For unit test in VelocityWeb, you need to write a new controller, for example: public class TestPetStoreController extends PetStoreController { private Log log = LogFactory.getLog(this.getClass()); protected Object getDataSource() { log.debug("getDataSourceByDBCP"); BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl("jdbc:postgresql:jpetstore"); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUsername("postgres"); dataSource.setPassword("postgres"); return dataSource; } }Normally, database connection is get by JNDI lookup in runtime application. For unit test, we can use Apache DBCP to provide connection pool. If other functions in appliciton controller class not suitable for unit test, you must overwrite them. You should also write a new base test case: public class VPetStoreDispatcherTestCase extends VelocityWebTestCase { Log log = LogFactory.getLog(this.getClass()); protected void setUp() throws Exception { super.setUp(); } public ControllerServlet getControllerServlet() { return new PetStoreControllerServlet() { public Controller getController() { return new TestPetStoreController(); } }; } public void login(String userId, String password) throws ServletException, IOException { addRequestParameter("username", userId); addRequestParameter("password", password); String url = DispatcherTreeManager.getUrl(LoginProcessDispatcher.class); addRequestParameter("target_dispatcher_url", url); this.doPost(); Object user = this.getController().getSessionUser(getRequest()); log.debug(user); } public void logout() { } }In above code, method addRequestParameter() is used to simulate user input in web pages. It can also be used to simulate HTML hidden fields in web pages. And now, you can write your own test case: public void testLogin() { try { this.newHttpSession(); newHttpRequest(ShowProcessResultDispatcher.class); // createResponse(); login("j2ee", "j2ee"); // after login, the session should have user object Object sessionUser = this.getController().getSessionUser(getRequest()); assertNotNull(sessionUser); assertProcessSuccess(); //log.debug(getResponseText()); assertContainsResponseString("success"); } catch (Exception e) { log.error(e.getMessage(), e); } } public void testLoginBadPassword() {
If you run many test case in one time, the better way is to write all fail response to local files. |
|||