您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 >
使用JUnit對EJB進(jìn)行單元測試
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2013/3/20 14:35:53 ] 推薦標(biāo)簽:

使用下列步驟創(chuàng)建一個(gè) EJB 測試案例。

  通過繼承 JUnit.framework.TestCase 類創(chuàng)建一個(gè)測試類。命名約定:如果 bean 的名稱是 SampleEjbBean ,則將測試類命名為 SampleEjbBeanTest 。例如:

  public class SampleEjbBeanTest extends JUnit.framework.TestCase{ 。

  創(chuàng)建 Bean 的一個(gè) remoteInterface 類型的類變量。例如:

  SampleEjb remoteInterface

  創(chuàng)建測試類的一個(gè)靜態(tài)實(shí)例: static {

  instance = new SampleEjbBeanTest("");

  }

  因?yàn)樵搶?shí)例被用來作為 TestRunner 的 run 方法的一個(gè)參數(shù)以執(zhí)行 TestClass.main 方法和測試案例,所以您可以在 SwingUI 或者 TextUI 中執(zhí)行測試案例:

  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 {

  //formatting the Output

  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());

  }

  }

  接著,創(chuàng)建一個(gè)用于連接運(yùn)行在服務(wù)器上的 EJB bean 的方法并為遠(yuǎn)程接口創(chuàng)建句柄:

  將初始上下文添加到 HashMap 中。例如:

  env.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.ejs.ns.jndi.CNInitialContextFactory

  將 URL 添加到 HashMap 中。例如:

  env.put(Context.PROVIDER_URL, "iiop://localhost:900");

  創(chuàng)建 InitialContext 對象。例如:

  javax.naming.InitialContext ic =new javax.naming.InitialContext(env);

  通過在命名服務(wù)器中查找 EJB Alias 名稱來構(gòu)造 Bean 的一個(gè) homeInterface 例如:

  SampleEjbHome homeInterface = (SampleEjbHome) ic.lookup("SampleEjb");

  通過調(diào)用 homeInterface 的 create 方法創(chuàng)建一個(gè) remoteInterface 。 例如:

  remoteInterface = homeInterface.create(); Public void getConnection()

  {

  getinfo("Running " + this.toString());

  java.util.Hashtable env = new Hashtable();

  //Adding the Initial Context to the HashMap.

  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");

  javax.naming.InitialContext ic =new javax.naming.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");

  getinfo(e.toString());

  fail();

  }

  }

上一頁12下一頁
軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd