ps0604
ps0604

Reputation: 1081

Mocking an EJB inside another EJB with Mockito

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 aMyClass` 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?

Upvotes: 0

Views: 995

Answers (1)

Sergiy Dakhniy
Sergiy Dakhniy

Reputation: 608

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);
}

Upvotes: 1

Related Questions