針對 VisualAge for Java 3.5.3 + JUnit 3.7 環境,闡述如何為已部署的 EJB 編寫單元測試案例,驗證業務邏輯正確性。
public class SampleEjbBeanTest extends junit.framework.TestCase {
private SampleEjb remoteInterface; // EJB Remote Interface
// 靜態實例供 TestRunner 使用
private static SampleEjbBeanTest instance;
static {
instance = new SampleEjbBeanTest("");
}
public static void main(String[] args) {
if (args.length > 0) {
if (args[0].equals("SWING")) {
junit.swingui.TestRunner.run(instance.getClass());
} else {
junit.textui.TestRunner.run(instance.getClass());
}
} else {
System.out.println("************************************");
String className = instance.getClass().getName();
className = className.substring(className.lastIndexOf(".") + 1);
System.out.println("Test Report of: " + className);
System.out.println("************************************");
junit.textui.TestRunner.run(instance.getClass());
}
}
public void getConnection() {
getinfo("Running " + this.toString());
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.ibm.ejs.ns.jndi.CNInitialContextFactory");
env.put(Context.PROVIDER_URL, "iiop://localhost:900");
try {
getinfo("Creating an initial context");
InitialContext ic = new InitialContext(env);
getinfo("Looking for the EJB SampleEjb");
SampleEjbHome homeInterface = (SampleEjbHome) ic.lookup("SampleEjb");
getinfo("Creating a new EJB instance");
remoteInterface = homeInterface.create();
} catch (NamingException e) {
getinfo(e.toString());
fail();
} catch (Exception e) {
getinfo("Create Exception: " + e);
fail();
}
}
public void setUp() throws Exception {
getConnection(); // 每個測試方法前建立 EJB 連線
}
public void testAddition() {
try {
int result = remoteInterface.addition(10, 15);
getinfo("----------------------------------");
getinfo("Success without Exception");
assertEquals(25, result);
} catch (Exception e) {
fail("Fail: " + e);
System.out.println("Error: " + e);
}
}
public void getinfo(boolean msg) { System.out.println(msg); }
public void getinfo(String msg) { System.out.println(msg); }
}
main 方法。************************************
Test Report of: SampleEjbBeanTest
************************************
. Running testAddition(com.prudential.retserv.chart.servlet.SampleEjbBeanTest)
Creating an initial context
Looking for the EJB SampleEjb
Creating a new EJB instance
----------------------------------
Success without exception
Time: 15.984s
OK (1 tests)
| 優點 | 限制 |
|---|---|
| 加速開發、提升代碼品質 | 不分離測試數據與代碼 |
| 自我驗證、即時回饋 | 無法單元測試 Swing GUI、JSP、HTML |
| 測試套件層次化組織 | 不能替代功能/整合測試 |
| 廉價、易寫、Java 原生 | 無法直接測試伺服器端 Java 代碼(需 Cactus 等擴展框架) |
| 基於 Command + Composite 模式 | |
| 免費開源 |
單元測試是降低開發風險、提升代碼質量的關鍵實踐。在 EJB 開發前先寫測試套件(TDD),配合 JUnit 框架,能構建強有力的驗證與回歸保護網。即使環境限制(如 VisualAge + WebSphere),透過遠程調用真實容器中的 EJB,依然能實現有效的單元測試。