shift66
shift66

Reputation: 11958

How to test with PowerMock a method which calls another private void method from the same class?

I have a class which have some methods like in the example.

public class TestClass {

    public boolean aMethod()
    {
        voidMethod();
        return true;
    }

    private void voidMethod()
    {
        ... does something ...
    }

    ... other methods ...
}

I want to test aMethod with powermock and all methods should work normally except the voidMethod. I've created a partial mock of TestClass to make voidMethod do nothing.But I don't know how to expect call of this method.

testObject = createPartialMock(TestClass.class, "voidMethod");
expectPrivate(testObject, "voidMethod");

I'm getting an error on second line:

The method expect(T) in the type EasyMock is not applicable for the arguments (void)

How can I fix this issue?

Upvotes: 3

Views: 7499

Answers (2)

hotshot309
hotshot309

Reputation: 1728

It looks like PowerMock can't mock a private void method (only private methods with a value returned). They should really provide a more useful compiler error to explicitly say that. EasyMock doesn't mock private methods at all. @StanislawLeventhal's answer references the syntax for expecting (recording) calls to a non-private void method using EasyMock.

What you should do first is consider whether what you are trying to do makes sense, and what really needs to be mocked. Consider it a code smell when you are mocking a private method; maybe you need to do it, but usually, there is a way to avoid it. It sounds obvious to think critically about why you are mocking, but it's easy to get confused and miss things.

Why should you have a private method in your test class that you can't directly call and need to mock instead, but which doesn't return a value? Mocking is normally used to control what is returned from a method; here, you are basically saying that this method must be called, but you want to override its implementation with nothing (if I understand correctly). I'm not sure I can think of a situation where this would be useful or necessary in a test class. The example you provided is too generalized to understand the reasoning behind, but you should try to see if there is a better way to achieve your goal.

Upvotes: 2

Stanislav Levental
Stanislav Levental

Reputation: 2235

Use simple call like this:

testObject.voidMethod(); // don't use "expect" for voids
expectLastCall().times(3); // use this for expectations

And don't forget reply() after all you expectations and verify() after running tested code.

Upvotes: 2

Related Questions