使用下列步驟創(chuàng)建一個(gè) EJB 測(cè)試案例。
通過(guò)繼承 JUnit.framework.TestCase 類創(chuàng)建一個(gè)測(cè)試類。命名約定:如果 bean 的名稱是 SampleEjbBean ,則將測(cè)試類命名為 SampleEjbBeanTest 。例如:
public class SampleEjbBeanTest extends JUnit.framework.TestCase{ 。
創(chuàng)建 Bean 的一個(gè) remoteInterface 類型的類變量。例如:
SampleEjb remoteInterface
創(chuàng)建測(cè)試類的一個(gè)靜態(tài)實(shí)例: static {
instance = new SampleEjbBeanTest("");
}
因?yàn)樵搶?shí)例被用來(lái)作為 TestRunner 的 run 方法的一個(gè)參數(shù)以執(zhí)行 TestClass.main 方法和測(cè)試案例,所以您可以在 SwingUI 或者 TextUI 中執(zhí)行測(cè)試案例:
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 對(duì)象。例如:
javax.naming.InitialContext ic =new javax.naming.InitialContext(env);
通過(guò)在命名服務(wù)器中查找 EJB Alias 名稱來(lái)構(gòu)造 Bean 的一個(gè) homeInterface 例如:
SampleEjbHome homeInterface = (SampleEjbHome) ic.lookup("SampleEjb");
通過(guò)調(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();
}
}