Is it possible to use "PowerMockito.whenNew()" only for first occurence?

1.4k views Asked by At

I'm about to build up a JSON object and want to test the result. I'm calling a public method. There several private methods and a recursive call is made. Somewhere at the beginning I have this:

JSONObject obj = new JSONObject();

This is my "root" object. Unfortunately it is not given as a parameter or such, but created with constructor as shown. Within the recursvie call this constructor gets being called several more times to build the structure. What I need is the root object for assertion in test.

So I tried to get it somehow and tried this approach here ... following code:

JSONObject json = new JSONObject();
PowerMockito.whenNew(JSONObject.class).withNoArguments().thenReturn(json);

[...]

assertThat(json.get("bla"), is("hello")); // assertions possible to my root json object

This would me allow to have the built up root json object after execution for my assertions. BUT I run into a stackoverflow Exception. Why? Because the recursivly called constructors get now passed my root object insead calling the constructor.

So bottomline, what I need here: I want to say "whenNew(JSONObject.class, times(1))" or something similar. So that only the first constructor call gets mocked, and the following not anymore. I thought this should be possible, but can't find a way to achieve this :(

Thanks for any help, guys!

1

There are 1 answers

0
Raphael Amoedo On

I had the same issue. I had a main JSONObject and some of inner JSONObjects, but I only wanted the first one, and the others could work as usual. Basically, you have to set the instances after the first time too.

final JSONObject requestJSON = new JSONObject();
final JSONObject innerJSONExample = new JSONObject();
final JSONObject anotherInnerJSONExample = new JSONObject();

PowerMockito.whenNew(JSONObject.class).withNoArguments()
   .thenReturn(requestJSON)      //first return
   .thenReturn(innerJSONExample) //second return
   .thenReturn(anotherInnerJSONExample); //third return and so on...
//I will not use innerJSONExample and the other, but this is needed

It's important to mention that you must create the instances BEFORE the whenNew. Also, you CANNOT do this:

PowerMockito.whenNew(JSONObject.class).withNoArguments()
   .thenReturn(requestJSON)      //first return
   .thenReturn(new JSONObject()); //second return

Because you've already set that when "new JSONObject()" return "requestJSON", then, when you do this, you're returning the same "requestJSON", and you might get StackOverflowError.