[英]Mockito always returns null as a result of calling an EJB
I'm trying to call the second method of this class, and always get null
.我试图调用这个 class 的第二种方法,并且总是得到
null
。 Note that it returns new User()
however in the test class I always get null
:请注意,它返回
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();
}
}
And the test class:以及测试 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
}
}
Also, note that System.out.println
is never printed.另外,请注意
System.out.println
从不打印。 How to fix this to actually make a call to dao.readByUserid()
?如何解决此问题以实际调用
dao.readByUserid()
?
If you need to test the method of some class, and inside of it the other method of the same class is called which you want to mock, then you need to use @Spy
:如果您需要测试某些 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);
}
}
Note that I slightly modified the line with mocking getConnFromPool
because it's required when you use that technique.请注意,我使用 mocking
getConnFromPool
稍微修改了该行,因为使用该技术时需要它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.