Ankit Khettry
Ankit Khettry

Reputation: 1027

JUnit: Intercepting a method call and then invoking with different params

I am working on junit and using PowerMockRunner to mock static methods.

I am aware that static methods can be mocked using when(...).thenReturn(...)

I need to mock a certain method that takes four arguments:

public static void addInputPath(String, Boolean, Integer, Double)

I need the third parameter(Integer) in any call to this method to be replaced by, say 10. All other parameters should just be passed as is.

In other words, I need to do something like this:

when(addInputPath(str, bool, intgr, dbl)).thenReturn(addInputPath(str, bool, 10, dbl));

Is there a way to do this?

Upvotes: 2

Views: 2290

Answers (1)

GhostCat
GhostCat

Reputation: 140613

So, when I get your requirements right, what you actually want to do is to intercept the call to addInputPath() and invoke it with a different parameter?

If so: I am not sure if this can be done with any mocking framework (and I doubt that it is possible). Mocking frameworks are about mocking calls; not about instrumenting/intercepting calls.

Coming back to your problem, this is a nice example why static calls far too often cause problems. Thus, the best solution in my eyes would be to change your method xyz() to avoid that thing calling addInputPath() directly. Like this:

interface InputPathAdder {
   void addInputPath(str, ... );
}

class ForwardingInputPathAdder implements InputPathAdder {
   // implements the method by calling the static method

and all of a sudden, you can also do:

class ForwardingInputPathAdderWithFixedIntegerParm implements InputPathAdder {
   // implements the method by calling the static method, but using 10 always

( obviously, naming could be improved here )

And now: you use dependency injection to give your "class under test" some Object implementing InputPathAdder. This could be either one that is completely mocked for testing; or it could be one that just does forwarding (in your production environment; or it could be the one that fixes the 3rd parameter). And no need for mocking for your "intercept" situation.

Upvotes: 1

Related Questions