Here is a abstract class to extends MockEJB, it's very useful and powerful for testing ejb.
- package com.test.test.web.test.action;
- import javax.naming.Context;
- import javax.naming.InitialContext;
- import junit.framework.TestCase;
- import org.mockejb.MockContainer;
- import org.mockejb.SessionBeanDescriptor;
- import org.mockejb.jndi.MockContextFactory;
- import com.sybase.jdbc2.jdbc.SybDataSource;
- public abstract class AbstractMockEJBTest extends TestCase {
- private Context context;
- private MockContainer mockContainer;
- /**
- * Initial context
- */
- protected void setUp() throws Exception {
- MockContextFactory.setAsInitial();
- context = new InitialContext();
- mockContainer = new MockContainer(context);
- }
- /**
- * Retrieve the context
- *
- * @return context
- */
- protected Context getContext() {
- return context;
- }
- /**
- * Deploy the SessionBean to the mock container
- *
- * @param jndi
- * Jndi name
- * @param home
- * Home interface
- * @param remote
- * Remote interface
- * @param bean
- * Concrete class
- * @throws Exception
- */
- public void deploySessionBean(String jndi, Class home, Class remote, Class bean) throws Exception {
- SessionBeanDescriptor descriptor = new SessionBeanDescriptor(jndi, home, remote, bean);
- mockContainer.deploy(descriptor);
- }
- /**
- * Bind datasource to the context
- *
- * @param jndi
- * Jndi name
- * @param serverName
- * Server name
- * @param port
- * port
- * @param databaseName
- * Database name
- * @param user
- * user
- * @param password
- * password
- * @throws Exception
- */
- public void bindDataSource(String jndi, String serverName, int port, String databaseName, String user, String password) throws Exception {
- SybDataSource ds = new SybDataSource();
- ds.setServerName(serverName);
- ds.setPortNumber(port);
- ds.setDatabaseName(databaseName);
- if (user != null)
- ds.setUser(user);
- if (password != null)
- ds.setPassword(password);
- context.rebind(jndi, ds);
- }
- public void tearDown() {
- MockContextFactory.revertSetAsInitial();
- }
- }
How to use:
- public class EJBTest extends AbstractMockEJBTest {
- private TestDAOLocalHome testDAOHome;
- private TestDAOLocal testDAOLocal;
- protected void setUp() throws Exception {
- super.setUp();
- super.deploySessionBean("test/biz@version@/ejb/test/TestDAOLocal", TestDAOLocalHome.class, TestDAOLocal.class, TestDAOEJB.class);
- super.bindDataSource("test/jdbc/TESTDB", "192.168.0.1", 1000, "TEST", "test", "test");
- testDAOHome = (TestDAOLocalHome) super.getContext().lookup("test/biz@version@/ejb/test/TestDAOLocal");
- testDAOLocal = testDAOHome.create();
- }
- public void testDAO() throws Exception {
- Map returnMap = testDAOLocal.getCountryMap();
- assertNotNull(returnMap);
- assertEquals("CHINA", returnMap.get("CN"));
- }
- }