1.0          其他語言
 
 

5.3 在 VelocityWeb 中不用伺服器進行 J2EE 單元測試

 
 

在 VelocityWeb 中,你可以不用啟動 J2EE 伺服器,進行 J2EE 單元測試。這可以讓發展比以前更快。

為了在 VelocityWeb 中的進行單元測試,你需要寫一個新的控制器類,比如︰

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;
    }
}
一般情況下,資料庫連接是在應用程式執行時刻透過 JNDI 尋找得到的。對于單元測試,我們可以使用 Apache DBCP 來提供連接池。如果應用程式控制器類的其他函數對于單元測試也不適用,你也需要改寫 (overwrite) 它們。

你需要寫一個新的測試案例(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() {

    }

}
在以上代碼中,函數 addRequestParameter() 用來類比使用者在網頁上的輸入,它可以用來類比 HTML 網頁上的隱藏域(hidden fields)。

現在,你可以寫自己的測試案例了︰

    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() {
try {
this.newHttpSession();
newHttpRequest(ShowProcessResultDispatcher.class);
// createResponse();
login("j2ee", "j2ee_abc");
assertProcessFail();
assertContainsResponseString("error");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}


你也可以將 HTTP 回應文字寫到本地檔案中,然後檢查。

如果你一次執行多個測試案例,更好的辦法是將所有失敗的 HTTP 回應文字寫到本地檔案中。