使用JUnit对EJB进行单元测试

发表于:2008-3-06 16:47

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:网络转载

使用下列步骤创建一个 EJB 测试案例。

  通过继承 JUnit.framework.TestCase 类创建一个测试类。命名约定:如果 bean 的名称是 SampleEjbBean ,则将测试类命名为 SampleEjbBeanTest 。例如:

  public class SampleEjbBeanTest extends JUnit.framework.TestCase{ 。

  创建 Bean 的一个 remoteInterface 类型的类变量。例如:

  SampleEjb remoteInterface

  创建测试类的一个静态实例: static {

  instance = new SampleEjbBeanTest("");

  }

  因为该实例被用来作为 TestRunner 的 run 方法的一个参数以执行 TestClass.main 方法和测试案例,所以您可以在 SwingUI 或者 TextUI 中执行测试案例:

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

  }

  }

  接着,创建一个用于连接运行在服务器上的 EJB bean 的方法并为远程接口创建句柄:

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

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

  将 URL 添加到 HashMap 中。例如:

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

  创建 InitialContext 对象。例如:

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

  通过在命名服务器中查找 EJB Alias 名称来构造 Bean 的一个 homeInterface 例如:

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

  通过调用 homeInterface 的 create 方法创建一个 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();

  }

  }

 

22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号