Issue
I have a main EJB that injects a DAO EJB:
@Stateless
@LocalBean
public class MainEjb {
@Inject
private DaoEjb dao;
public MyClass someMethod(int i) {
return dao.read(i);
}
}
@Stateless
@LocalBean
public class DaoEjb {
public MyClass read(int i){
// get MyClass object using jdbc
return object;
}
}
Now, I want to test MainEjb.someMethod()
using jUnit + Mockito, injecting in the test the real MainEjb
, and mocking the DaoEjb.read() method to return a
MyClass` object (instead of making a jdbc call):
@RunWith(MockitoJUnitRunner.class)
public class UserBeanUnitTest {
@InjectMocks
private MainEjb bean;
DaoEjb dao = mock(DaoEjb.class);
@Test
public void testBean() {
MyClass object = new MyClass();
// set object fields
assertThat(bean.someMethod(1)).isEqualTo(object);
}
}
The problem is that I don't know how to connect the bean
and dao
beans, so this doesn't work. I know I can do this with Arquillian, but I'm trying to avoid instantiating a container. Can this be done with Mockito
?
Solution
Your example worked for me. I just added a rule for dao:
@Test
public void testBean() {
MyClass object = new MyClass();
// set object fields
Mockito.when(dao.read(Matchers.eq(1))).thenReturn(object);
assertThat(bean.someMethod(1)).isEqualTo(object);
}
Answered By - Sergiy Dakhniy