Hi I have a question related to MockEJB. I need to write unit tests to test a code that is calling a EJB. I use Mockito to write a mock for the EJB, and MockEJB to simulate the JNDI context.
My tests look like this :
@Test
public void test1() throws Exception {
// create a mock instance
NetworkManager aMockManager = createMockNetworkManager();
// deploy it in mock container and register it in JNDI
registerMockNetworkManager(aMockManager);
// encapsulates the JNDI lookup
NetworkManager manager = NetworkManagerAccessor.getNetworkManager();
// call a method
manager.deleteObject(new TopicId(-1), null, this.userContext);
// verify that the method was called on the mock
verify(aMockManager).deleteObject(new TopicId(-1), null, this.userContext);
}
@Test
public void test2() throws Exception {
// create a mock instance
NetworkManager aMockManager = createMockNetworkManager();
// deploy it in mock container and register it in JNDI
registerMockNetworkManager(aMockManager);
// encapsulates the JNDI lookup
NetworkManager manager = NetworkManagerAccessor.getNetworkManager();
// call a method
manager.deleteDataItem(new DataItemId(-1), null, null, null);
// verify that the method was called on the mock
verify(aMockManager).deleteDataItem(new DataItemId(-1), null, null, null);
}
The first test runs fine, however the second test systematically fails (mockito says the expected method was not called) While debugging, I can see that the second time I attempt to deploy the mock EJB to the JNDI, it is not deployed, and the first mock object is still there. So in fact the second test is fecthing from the JNDI the mock created in the first test. Note also that if I run the second test alone (by commenting the first one), it runs fine.
My setup and clean method look like this :
@Before
public void setupMockJNDI() {
try {
// setup mockEJB
MockContextFactory.setAsInitial();
Context jndiContext = new InitialContext();
// create the mock container
mockContainer = new MockContainer( jndiContext );
} catch (NamingException e) {
e.printStackTrace();
}
}
@After
public void unregisterJNDI() {
// reset mock context
MockContextFactory.revertSetAsInitial();
}
I really don't understand what happens, my tests look very similar to the mock EJB examples. Does anyone have an idea ?
Thanks