Testing constructors with powermock

2019-08-01 06:25发布

问题:

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
    }
}

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

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

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.

Anyone know of any ways?

回答1:

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".

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).