EJB3Unit is able to inject to annotated fields (using EJB 3 (JSR 220) annotations), mock objects. The MockedSessionBeanTest can be used to automate the dependency injection and execute easily test with mocked dependencies - to test beans in isolation!
THe above example shows a session bean with annotated fields. To test this class in isolation we want to inject mock objects for each annotated field.
@Stateless
public class MySessionBean implements IMySessionBean {
@Resource(name = "java:/MSSqlDS")
private DataSource ds;
@Resource
private SessionContext ctx;
@PersistenceContext
private EntityManager manager;
...
public void test_executeOperation() {
}The basic test can be configured by extending the MockedSessionBeanTest class. The next example shows how to test the session bean MySessionBean:
public class MockedSessionBeanTest extends
MockedSessionBeanTest<MySessionBean> {
/**
* Constructor.
*/
public MyockedSessionBeanTest() {
super(MySessionBean.class);
}
}In the test method test_executeOperation() we can we define expectations on the mock DataSource ds that specify the methods that we expect to be called upon it during the test run.
public void test_executeOperation() {
final DataSource ds = getMock(DataSource.class);
context.checking(new Expectations() {{
atLeast(1).of(ds).getDs();
will(returnValue(null));
}});
// call the expected operation
toTest.executeOperation();
}With the method getMock(type) we can retrieve the instance which will be injected when ejb3unit constructs the session bean (members annotated with @EJB, @Ressource ...). In this case we get the data source which was injected to the field
@Resource(name = "java:/MSSqlDS")
private DataSource ds;Please read the excellent documentation of the JMock project