Steve
Steve

Reputation: 4701

Verify a void method was called inside a private method with EasyMock/PowerMock

I have a method that looks like this (simplification)

private boolean x = someMethodToSetTheValueOfX();

private void method(args){
        if(x){
             method1();
        }else{
             method2();
        }
}

I want to write a unit test to guarantee that when x is true, method1 is called. I know I can use PowerMock's Whitebox to set the value of x and invoke the method, but how can I confirm that method1() was called? Note that method1() is void.

I am not allowed to use another framework (like Mockito) besides EasyMock/PowerMock.

Upvotes: 2

Views: 615

Answers (2)

GhostCat
GhostCat

Reputation: 140523

You are getting this wrong; that is not how you should be designing your tests.

First of all: be careful about using PowerMock... frameworks. They rely on byte code manipulation; and sooner or later that calls for trouble. The only reasonable situation to user PowerMock(ito) is when you have to test legacy production code. In any other situation: change your production code so it can be tested easily.

Then: do not test your code this way!

You use a mocking framework to create/control those objects that you pass to your "class under test". You don't use the framework to directly test your "class under test"! More specifically: you don't want to write test code that knows about private methods - those are implementation details.

What you do instead:

a) as said, you can use mocking to pass objects into your class under test. And then you can control/verify those mocks see the calls that you expect your "class under test" to make. So, worst case, you could put method1/2 on a different object; and then you can use mock/verify to check if they were called as expected.

b) you create objects of your "class under test" ... and then "assert" on the properties of those objects; or on results that method calls return.

Upvotes: 0

Dak31
Dak31

Reputation: 82

You can either use:

System.out.println("method one was called"); 

If you can print to a consol in an IDE like eclipse, or use:

JOptionPane.showMessageDialogue(null, "method one was called");

And put them inside method1

Upvotes: 1

Related Questions