[英]How to mock another class method call from the method being tested using powermock-easymock?
I'm using easymock and powermock to write unit test case for the below isRegisteredUSer() of Class B. How to mock getUserInformation() of Class A and return a mocked UserAccessBean? 我正在使用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();
}
}
Even If I use EasyMock.expect() to mock getUserInformation() method call, my console is going inside getUserInformation() when I run my JUnit. 即使我使用EasyMock.expect()模拟getUserInformation()方法调用,但在运行JUnit时,我的控制台仍在getUserInformation()中。
Can someone please help me to mock another class functions method (Class A's getUserInformation) call from the method (Class B's isRegisteredUSer) being tested? 有人可以帮我模拟来自正在测试的方法(类B的isRegisteredUSer)的另一个类函数方法(类A的getUserInformation)调用吗?
Please, next time copy actual working code. 请下次复制实际的工作代码。 Your code has many typos and anomalies that makes it hard to workaround. 您的代码有很多错别字和异常,这使得解决方法变得很困难。
Nevertheless, I think you want a normal EasyMock for A
and a mock on new for B
. 尽管如此,我认为您想要A
的普通EasyMock和B
new的模拟。 The code below should answer your question 以下代码可以回答您的问题
@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();
}
}
I will however highly recommend A
to be injected into B
and to get rid of the static method. 但是,我强烈建议A
注入B
并摆脱静态方法。 That will get rid of PowerMock and simplify the code. 这将摆脱PowerMock并简化代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.