比較古老的項目,用Struts,Spring的架構的,想做單元測試功能,能從action開始測邏輯的,網上找了個叫StrutsTestCase的工具包(https://sourceforge.net/projects/strutstestcase/),結合Junit可以實現,注意選擇正確版本,不同Struts版本需要下載不同的包,按例子來做很方便,包括數據庫的操作也是真實去做的。
// StrutsTestCase - a JUnit extension for testing Struts actions
// within the context of the ActionServlet.
// Copyright (C) 2002 Deryl Seale
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Apache Software License as
// published by the Apache Software Foundation; either version 1.1
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// Apache Software Foundation Licens for more details.
//
// You may view the full text here: http://www.apache.org/LICENSE.txt
package examples;
import servletunit.struts.MockStrutsTestCase;
public class TestLoginAction extends MockStrutsTestCase {
public TestLoginAction(String testName) {
super(testName);
}
public void setUp() throws Exception {
super.setUp();
setInitParameter("validating","false");
setConfigFile("/WEB-INF/xxx/struts-config.xml");
}
public void testSuccessfulLogin() {
addRequestParameter("username","deryl");
addRequestParameter("password","radar");
setRequestPathInfo("/login");
actionPerform();
verifyForward("success");
verifyForwardPath("/main/success.jsp");
assertEquals("deryl",getSession().getAttribute("authentication"));
verifyNoActionErrors();
}
public void testFailedLogin() {
addRequestParameter("username","deryl");
addRequestParameter("password","express");
setRequestPathInfo("/login");
actionPerform();
verifyForward("login");
verifyForwardPath("/login/login.jsp");
verifyInputForward();
verifyActionErrors(new String[] {"error.password.mismatch"});
assertNull(getSession().getAttribute("authentication"));
}
public static void main(String[] args) {
junit.textui.TestRunner.run(TestLoginAction.class);
}
}