由于调用 EJB,Mockito 总是 returns null

Mockito always returns null as a result of calling an EJB

我正在尝试调用这个 class 的第二个方法,并且总是得到 null。请注意,它 returns new User() 但是在测试中 class 我总是得到 null:

@Stateless
public class UserDAO2 {

    public Connection getConnFromPool(int i) {
        return null;
    }

    public User readByUserid(String s) {
        System.out.println("In DAO 2");
        Connection c = getConnFromPool(1);
        return new User();
    }
}

和测试class:

@RunWith(MockitoJUnitRunner.class)
public class UserBeanUnitTest {

    @InjectMocks
    private UserDAO2 dao2;

    @Before
    public void setup() {
        dao2 = Mockito.mock(UserDAO2.class);
        MockitoAnnotations.initMocks(this);
    }


    @Test
    public void testBean() {

        Mockito.when(dao2.getConnFromPool(1)).thenReturn(null);

        User expectedUser = new User();
        expectedUser.setSk(1);
        expectedUser.setFirstName("David");
        expectedUser.setLastName("Gahan");
        expectedUser.setUserid("user1");

        User user = dao2.readByUserid("user1"); // <-- this method always returns null

        assertThat(user).isEqualTo(expectedUser); // <-- test fails as expectedUser != null

    }

}

另外,请注意 System.out.println 永远不会被打印出来。如何解决此问题以实际调用 dao.readByUserid()

如果你需要测试一些class的方法,并且在其中调用了你想要模拟的相同class的另一个方法,那么你需要使用@Spy:

@RunWith(MockitoJUnitRunner.class)
public class UserDAO2Test {

    @InjectMocks
    @Spy
    private UserDAO2 dao;

    @Test
    public void testBean() {

        Mockito.doReturn(null).when(dao).getConnFromPool(1);

        User expectedUser = new User();
        expectedUser.setSk(1);
        expectedUser.setFirstName("David");
        expectedUser.setLastName("Gahan");
        expectedUser.setUserid("user1");

        User user = dao.readByUserid("user1");

        assertThat(user).isEqualTo(expectedUser);
    }
}

请注意,我用 mocking getConnFromPool 稍微修改了这一行,因为当您使用该技术时它是必需的。

有关间谍活动,请参阅 docs