简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM