From Gossip@caterpillar

JUnit Gossip: 一個測試實例

這邊以 JSP/Servlet 版面下的一個「JSP/Servlet 與 Model 2 架構」實例來進行HttpUnit功能單元測試,我們將測試該實例的工作流程是否符合我們的預期,即預設顯示歡迎頁面、登入錯誤時顯示"WEB- INF/pages/fail.jsp",而登入正確時顯示"WEB-INF/pages/success.jsp"。

以下是測試案例實際內容:

  • Model2DemoTest.java
package onlyfun.caterpillar.test;

import java.io.IOException;
import java.net.MalformedURLException;

import org.xml.sax.SAXException;

import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebResponse;

import junit.framework.TestCase;

public class Model2DemoTest extends TestCase {
private WebConversation webConversation;
private WebResponse response;

protected void setUp() throws Exception {
super.setUp();
webConversation = new WebConversation();
response = webConversation.getResponse(
"http://localhost:8080/model2Demo/index.action");
}

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

public void testWelcomePage() throws
MalformedURLException,
IOException, SAXException {
assertEquals("Welcome", response.getTitle());
}

public void testSubmitWrongInfo() throws
SAXException, IOException {
WebForm form = response.getFormWithName("userForm");
form.setParameter("username", "guest");
form.setParameter("password", "guest");
WebResponse submitResponse = form.submit();
assertEquals("Fail", submitResponse.getTitle());
}

public void testSubmitCorrectInfo() throws
SAXException, IOException {
WebForm form = response.getFormWithName("userForm");
form.setParameter("username", "caterpillar");
form.setParameter("password", "123456");
WebResponse submitResponse = form.submit();
assertEquals("Success", submitResponse.getTitle());
}

public static void main(String[] args) {
junit.textui.TestRunner.run(Model2DemoTest.class);
}
}

為了可以測試工作流程是否符合預期,您透過一個簡單的標題文字來判斷,這是設計一個可測試頁面的實際例子,首先要確定的是工作流程無誤,之後再逐步增加頁面的資訊,這是測試驅動的基本原則。