使用下列步驟創(chuàng)建一個 EJB 測試案例。
通過繼承 JUnit.framework.TestCase 類創(chuàng)建一個測試類。命名約定:如果 bean 的名稱是 SampleEjbBean ,則將測試類命名為 SampleEjbBeanTest 。例如:
public class SampleEjbBeanTest extends JUnit.framework.TestCase{ 。
創(chuàng)建 Bean 的一個 remoteInterface 類型的類變量。例如:
SampleEjb remoteInterface
創(chuàng)建測試類的一個靜態(tài)實例: static {
instance = new SampleEjbBeanTest("");
}
因為該實例被用來作為 TestRunner 的 run 方法的一個參數(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)建一個用于連接運行在服務(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 的一個 homeInterface 例如:
SampleEjbHome homeInterface = (SampleEjbHome) ic.lookup("SampleEjb");
通過調(diào)用 homeInterface 的 create 方法創(chuàng)建一個 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();
}
}