【发布时间】:2017-08-25 18:36:23
【问题描述】:
我正在使用easymock和powermock为B类的以下isRegisteredUSer()编写单元测试用例。如何模拟A类的getUserInformation()并返回一个模拟的UserAccessBean?
class A{
private int userId;
A(int userId){
this.userId = userId;
}
public UserAccessBean getUserInformation(){
UserAccessBean userAB = new USerAccessBean().findByUserId(userId);
return userAB;
}
}
Class B{
public static boolean isRegisteredUSer(int userId){
A a = new A(userId);
UserAccessBean userAB = a.getUserInformation();
if(userAB.getUserType().equals("R")){
return true;
}
return false;
}
JUnit
public class BTest extends EasyMockSupport{
UserAccessBean userAB = null;
A a = null;
int userId = 12345;
@Before
public void setUp() throws Exception {
userAB = new UserAccessBean();
}
@Test
public void when_UserDesctiptionIsR_Expect_True_FromIsRegisteredUser() throws Exception{
//data setup
userAB.setDescription("R");
A a = new A(12345);
EasyMock.expect(a.isRegisteredUser()).andReturn(userAB);
PowerMock.replayAll();
Boolean flag = B.isRegisteredUser(userId);
assertEquals(flag, true);
PowerMock.verifyAll();
}
}
即使我使用 EasyMock.expect() 来模拟 getUserInformation() 方法调用,当我运行 JUnit 时,我的控制台也会进入 getUserInformation() 内部。
有人可以帮我模拟正在测试的方法(B 类的 isRegisteredUSer)调用的另一个类函数方法(A 类的 getUserInformation)调用吗?
【问题讨论】:
-
Powermock 提供了“mockNew”,但您应该重构代码以简化测试,请参阅github.com/powermock/powermock/wiki/mockconstructor
标签: java unit-testing junit powermock easymock