【问题标题】:How to mock another class method call from the method being tested using powermock-easymock?如何从使用 powermock-easymock 测试的方法中模拟另一个类方法调用?
【发布时间】: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)调用吗?

【问题讨论】:

标签: java unit-testing junit powermock easymock


【解决方案1】:

请,下次复制实际工作代码。您的代码有许多拼写错误和异常,难以解决。

尽管如此,我认为您希望为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 并简化代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多