如何使用PowerMockito在静态方法中模拟新的类实例

编程入门 行业动态 更新时间:2024-10-22 09:48:55
本文介绍了如何使用PowerMockito在静态方法中模拟新的类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个带有静态方法的类,在静态方法内部,我创建了另一个类的实例,并将其保存在地图中。我需要为此方法编写单元测试。最好的方法是什么?

I have a class with static method, inside the static method I creating an instance of a different class and save it inside a map. I need to write unit tests for this method. What is the best way to do it?

例如:

public class MyClass { public static synchronized void method (String str1, String str2, Object obj){ do something..... DifferentClass dc = new DifferentClass(str1,str2,obj); dc.methodCall(); do something..... } }

试图做到这一点:

DifferentClass dc = PowerMockito.mock(DifferentClass.class); PowerMockito.whenNew(DifferentClass.class).withArguments(str1,str2,obj).thenReturn(dc);

我在 dc.methodCall()中得到空指针异常;

And I am getting null pointer exception in dc.methodCall();

谢谢

推荐答案

请确保您拥有 @PrepareForTest 中的MyClass 。 另外,我建议使用 withParameterTypes 。这不是强制性的,但有助于避免某些错误。

Make sure that you have the MyClass in @PrepareForTest. Also, I recommend use the withParameterTypes. It's not mandatory, but it helps avoid some errors.

更多推荐

如何使用PowerMockito在静态方法中模拟新的类实例

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

发布评论

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

>www.elefans.com

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