Browse DevX
Sign up for e-mail newsletters from DevX


Unit Test Secured EJBs in Production : Page 2

Unit testing EJBs that are secured through permissions is complex. Learn how to unit test secured EJBs and EJB-based applications in the same production environment without needing to switch off the permission settings.


Run JUnitEE-Based Test Cases

To access and invoke methods on a secured EJB, you should first authenticate the remote call to the secured EJB. It then should have the proper role. In the case of IBM WebSphere Application Server, the test should be in the context of the container (i.e., the test effectively is in-container).

The following is the code for your JUnit test case in IBM WebSphere Application Server:

protected void setUp() throws Exception {
 	Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory"); env.put(Context.PROVIDER_URL,"iiop://localhost:4084/"); try { initialContext = new InitialContext(env); } catch (NamingException e) { e.printStackTrace(); } } protected void tearDown() throws Exception { super.tearDown(); try { initialContext.close(); } catch (NamingException e) { e.printStackTrace(); } initialContext = null; } public void test1 () throws Exception { TestFacadeHome home =
(TestFacadeHome)javax.rmi.PortableRemoteObject.narrow(initialContext.lookup("TestFacadeHome"),TestFacadeHome.class); TestFacade tFacade = home.create(); result = tFacade.someMethod(); // Do your testing here. assertNotNull(result); }

The remainder of the article shows you how to:

  1. Create a custom servlet based on the JUnitEE servlet, JUnitEEServlet
  2. Set up the environment for unit testing secured EJBs
  3. Run the unit tests

Once you've completed these steps, your sample code will read the environment settings of the IBM WebSphere Application Server, perform programmatic login into the application server, and then run the test cases in the authenticated context of the application server.

Thanks for your registration, follow us on our social networks to keep up-to-date