【发布时间】:2020-07-30 00:02:46
【问题描述】:
我在验证某些方法应该使用特定参数调用时使用 Mockito 是新手,而所有值类型参数(int、String、enum 等)都可以验证,但引用/类类型参数似乎不是,这是一个例子
// my actual class
public class MyActualClass {
public void processRequest() {
User curUser = MyUtils.getUserFromOtherPlace(UserType.ADMIN);
processAnotherRequest(1, "address", curUser);
}
public void processAnotherRequest(int userId, String address, User user) { ... }
}
public static class MyUtils{
public static getUserFromOtherPlace(UserType userType) {
User newUser = new User();
if (userType == UserType.ADMIN) {
newUser.setAccess(1);
}
//...
return newUser
}
}
// my test class
public class MyActualClassTest{
@Mock
private MyActualClass myActualClass;
@Test
public void testIfMethodBeingCalledCorrectly() {
User adminUser = new User();
adminUser.setAccess(1);
doCallRealMethod().when(myActualClass).processRequest();
myActualClass.processRequest();
verify(myActualClass).processAnotherRequest(1, "address", adminUser);
}
}
我知道这可能是因为我的测试方法中设置的 adminUser 与通过我的实际方法 getUserFromOtherPlace -> MyUtils.getUserFromOtherPlace 生成的引用对象不同,我还尝试用我的静态模拟返回对象方法如
// tried 1
when(MyUtils.getUserFromOtherPlace(UserType.ADMIN).thenReturn(adminUser); // this throws error like "You cannot use argument matchers outside of verification or stubbing", and suggest using eq()
// tried 2
when(MyUtils.getUserFromOtherPlace(eq(UserType.ADMIN)).thenReturn(adminUser); //this throws NullPointer exception in getUserFromOtherPlace when check the input enum parameter "userType"
那么我怎样才能将引用对象传递给我的入口方法并在这里模拟它作为我的内部方法的返回值呢?顺便说一句,如果我的方法只包含值类型参数,它会工作...
【问题讨论】:
标签: java unit-testing nullpointerexception mockito reference-type