使用Powermock测试构造函数 [英] Testing constructors with powermock

查看:607
本文介绍了使用Powermock测试构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道在powermock中有一种方法可以对构造函数进行单元测试并模拟构造函数调用的方法。

Does anybody know of a way in powermock you can unit test a constructor and mock the methods that the constructor calls.

即。我有一个这样的类;

i.e. I have a class like this;

public class myClass {
    public myClass(){
        myMethod();
        // do other stuff
    }
    public void myMethod(){
        // do stuff
    }
}

我要做的是为 myClass()构造函数编写单元测试模拟 myMethod()

What I want to do is write a unit test for myClass() constructor that mocks myMethod().

如果 myMethod()是静态的,因为我可以使用 mockStaticPartial()然后调用构造函数。

This would be easy if myMethod() was static as I could use mockStaticPartial() then invoke the constructor.

仅创建MyClass的部分模拟将不起作用,因为一旦创建了模拟,便会立即创建该模拟,一个新的MyClass实例,而没有模拟 myMethod()

Just creating a partial mock of MyClass won't work either as once I've created the mock I've created it, invoking the constructor at that point will just create a new instance of MyClass without myMethod() being mocked.

有人知道吗?

推荐答案

您不应模拟正在测试的类。如果构造函数调用方法,则应在测试构造函数的过程中测试方法的动作。如果该方法执行的内容超出了单元测试的范围,请模拟该方法用于执行填充的类。

You should not mock a class under test. If the constructor calls a method then the actions of the method should be tested as part of testing the constructor. If the method does stuff that is outside the scope of unit testing, mock the classes that method is using to do the "stuff".

如果您确实要执行此操作使用上面的内容,(我不建议您这样做),您可以创建要覆盖该方法的被测类的子类。 (这与johncarl上面的出色评论相反)。

If you REALLY want to do it with what you have above, (I don't recommend this) you could create a sub-class of your class under test that overrides the method. (this goes against johncarl's excellent comment above).

这篇关于使用Powermock测试构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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