如何使用easymock

编程入门 行业动态 更新时间:2024-10-28 04:17:06
本文介绍了如何使用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

本文发布于:2023-10-31 03:50:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544912.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   easymock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!