如何使用easymock-powermock模拟静态方法链调用? [英] How to mock static method chain call using easymock-powermock?

查看:153
本文介绍了如何使用easymock-powermock模拟静态方法链调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 easymock-powermock 模拟下面的方法链,

I want to mock below method chain using easymock-powermock,

OtherClass oc = SampleClass.getInstance().getSampleMethod(new StringReader("ABC");

getInstance() 是一个单例方法.getSampleMethod() 是一个公共方法.

getInstance () is a singleton method. getSampleMethod() is a public method.

当我尝试使用 expect/andReturn 获取 null 时.

When I try to use expect/andReturn getting null.

推荐答案

我不确定您是否立即为整个方法链设置了期望,但这不是它的工作原理.您必须分别为每个方法调用设置期望值.

I am not sure if you are setting the expectations at once to the whole method chain but that is not how it works. You have to set the expectation for each and every method call separately.

在您的情况下,由于第一个方法调用是静态调用,您应该使用 powermock 并设置期望并为其返回模拟实例.然后你应该添加对第二个方法调用的期望.我在下面给出了示例代码,请检查它是否适用于您的情况.

In your case, as first method call is a static call you should use powermock and set the expectation and return the mocked instance for it. Then you should add the expectation for second method call. I have given the sample code below Please check if it works in your case.

@RunWith(PowerMockRunner.class)
@PrepareForTest({SampleClass.class})
public class SimpleClassTest{
    @Test
    public void test(){
        PowerMock.mockStatic(SampleClass.class);
        SampleClass sampleClassInstance = EasyMock.createMock(SampleClass);
        EasyMock.expect(SampleClass.getInstance).andReturn(sampleClassInstance);
        EasyMock.expect(sampleClassInstance.getSampleMethod(/*required parameter goes here*/).andReturn(/*Otherclass instance goes here*/);
        PowerMock.replayAll();
        EasyMock.replay(sampleClassInstance);
    }

}

这篇关于如何使用easymock-powermock模拟静态方法链调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆