我正在使用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()。
有人可以帮助我从正在测试的方法(Class B的isRegisteredUSer)中模拟另一个类函数方法(Class A的getUserInformation)调用吗?
答案 0 :(得分:0)
请下次复制实际工作代码。您的代码有很多拼写错误和异常,这使得难以解决。
尽管如此,我认为您需要A
的普通EasyMock和B
的新模拟。以下代码应回答您的问题
@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class, B.class})
public class BTest extends EasyMockSupport {
UserAccessBean userAB = new UserAccessBean();
A a;
int userId = 12345;
@Test
public void when_UserDesctiptionIsR_Expect_True_FromIsRegisteredUser() throws Exception {
//data setup
userAB.setDescription("R");
A a = createMock(A.class);
expect(a.getUserInformation()).andReturn(userAB);
replayAll();
PowerMock.expectNew(A.class, userId).andReturn(a);
PowerMock.replay(A.class);
Boolean flag = B.isRegisteredUser(userId);
assertEquals(flag, true);
PowerMock.verifyAll();
verifyAll();
}
}
但我强烈建议A
注入B
并摆脱静态方法。这将摆脱PowerMock并简化代码。