JUnit 運行於獨立 JVM,無法直接調用本地 EJB,必須通過遠程介面測試。本文基於 NetBeans 5.x + Sun Java System App Server 8.1,演示會話 Bean 測試全流程。
$AS_HOME/lib/j2ee.jar、$AS_HOME/lib/appserv-rt.jar。AdminBean)。AdminBeanTest)。setSessionContext、ejbCreate 等),保留業務方法測試。// 1. 聲明遠程介面字段
private beantest.AdminRemote admin;
// 2. 右鍵 → Enterprise Resources → Call Enterprise Bean → 選 AdminSB
// IDE 生成 lookupAdminBean(),需修改為全域 JNDI 名
private beantest.AdminRemote lookupAdminBean() {
try {
Context c = new InitialContext();
Object remote = c.lookup("ejb/AdminBean"); // 全域 JNDI 名
AdminRemoteHome home = (AdminRemoteHome) PortableRemoteObject.narrow(remote, AdminRemoteHome.class);
return home.create();
} catch (Exception e) { throw new RuntimeException(e); }
}
// 3. setUp/tearDown 管理生命週期
protected void setUp() throws Exception { admin = lookupAdminBean(); }
protected void tearDown() throws Exception { admin.remove(); }
public void testGetString() throws RemoteException {
assertEquals("response:Test", admin.getString("Test"));
}
public void testGetInt() throws RemoteException {
assertEquals(15, admin.getInt(5, 3));
}
public void testGetVO() throws RemoteException {
assertEquals("Joe User", admin.getVO().getName()); // 修正預期值
}
@LocalBean 與 @EJB 注入,單元測試可直接 Mock 介面,無需容器。