【发布时间】:2017-02-20 11:43:05
【问题描述】:
我需要对一个方法进行单元测试,并且我想模拟该行为,以便我可以测试方法中代码的必要部分。
为此,我想访问由我尝试测试的方法中的私有方法返回的对象。我创建了一个示例代码来大致了解我想要实现的目标。
主类
Class Main {
public String getUserName(String userId) {
User user = null;
user = getUser(userId);
if(user.getName().equals("Stack")) {
throw new CustomException("StackOverflow");
}
return user.getName();
}
private User getUser(String userId) {
// find the user details in database
String name = ""; // Get from db
String address = ""; // Get from db
return new User(name, address);
}
}
测试类
@Test (expected = CustomException.class)
public void getUserName_UserId_ThrowsException() {
Main main = new Main();
// I need to access the user object returned by getUser(userId)
// and spy it, so that when user.getName() is called it returns Stack
main.getUserName("124");
}
【问题讨论】:
标签: java junit mockito junit4 powermock