简体   繁体   English

在使用PowerMock注入后,模拟一个Object的方法调用EasyMock

[英]Mocking an Object's method calls by EasyMock after injecting it using PowerMock

I have a following class in my project for which I am trying to write a test case 我在我的项目中有一个以下类,我正在尝试编写一个测试用例

Class A{
    a(){
        B b = new B();
        int ans = b.somefunction();
    }
}

I need to mock somefunction() call in above class for my test 我需要在上面的类中为我的测试模拟somefunction()调用

I tried following to achieve this 我试过以下来实现这一点

@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class,B.class})
Class TestA{
    testa(){
        EasyMock mb = EasyMock.createMock(B.class);
        PowerMock.createMock(B.class);
        PowerMock.expectNew(B.class).andReturn(mb);
        EasyMock.expect(mb.somefunction()).andReturn(0);
        EasyMock.replay(mb);
        PowerMock.replay(B.class);
    }
}

but it always gives Java.lang.AssertionError: Unexpected method call B.somefunction() 但它总是给出Java.lang.AssertionError:意外的方法调用B.somefunction()

I have PowerMock 1.5.5 and EasyMock 3.2 in my package 我的包中有PowerMock 1.5.5和EasyMock 3.2

Can someone help me with the above problem and help me figure out where exactly I am going wrong. 有人可以帮助我解决上述问题,并帮助我弄清楚我到底出错了什么地方。 I am new to using EasyMock and PowerMock. 我是使用EasyMock和PowerMock的新手。

Does there exist a simpler way to test given class. 是否存在测试给定类的更简单方法。

You are not executing test case properly,the constructor in test class is not needed 您没有正确执行测试用例,不需要测试类中的构造函数

the correct way would be to do it like this: 正确的方法是这样做:

@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class,B.class})
class TestA{
    B mb=EasyMock.createNiceMock(B.class); 
    PowerMock.expectNew(B.class).andReturn(mb).anyTimes();
    EasyMock.expect(mb.somefunction()).andReturn(0).anyTimes();
    EasyMock.replay(mb);
    PowerMock.replayAll();

    A a=new A(); //calling A's Constructor so that test case actually runs
}

hope this helps! 希望这可以帮助!

Good luck 祝好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM