首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

NetBeans IDE 測試 Enterprise Bean 實戰教程:JUnit + 遠程介面驗證

     編輯:Java 相關知識

JUnit 運行於獨立 JVM,無法直接調用本地 EJB,必須通過遠程介面測試。本文基於 NetBeans 5.x + Sun Java System App Server 8.1,演示會話 Bean 測試全流程。

環境準備

  • 安裝 SJS App Server 8.1,NetBeans 註冊 Server(Tools → Server Manager)。
  • 專案測試類路徑加入 $AS_HOME/lib/j2ee.jar、$AS_HOME/lib/appserv-rt.jar。

生成測試骨架

  1. 雙擊 Enterprise Bean 打開源碼(AdminBean)。
  2. Ctrl+Alt+J 生成 JUnit 測試類(AdminBeanTest)。
  3. 刪除生命週期方法測試(setSessionContext、ejbCreate 等),保留業務方法測試。

關鍵代碼注入:JNDI 查找遠程介面

// 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());  // 修正預期值
}

部署與運行

  1. 右鍵專案 → Deploy Project。
  2. Alt+F6 運行測試,輸出綠條表示通過。

遷移建議

  • 現代專案建議使用 Arquillian(容器內測試)或 Spring Boot Test + @SpringBootTest 替代遠程 JNDI 查找,簡化依賴與配置。
  • EJB 3.1+ 支援 @LocalBean 與 @EJB 注入,單元測試可直接 Mock 介面,無需容器。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved