Search code examples
javaunit-testingmockitojunit4

Is there a way to extract the instance and static variables used in a method, to get an idea of which objects require to be mocked


I am developing JUnit test cases involving Mockito.

There are many cases where lots of instance and static variables being used in methods.

It is quite tedious to manually inspect all the lines of code in a method to get an idea of the objects which require to be mocked, for a high level understanding.

I wonder if there is any easier way to extract the instance and static variables used in methods. I am also new to JUnit and Mockito. Thanks.


Solution

  • You are drawing the wrong conclusion.

    You find that it is hard to write good unit tests for your production code - because it contains so many things that require to be mocked.

    You want to fix that by somehow automatically mock everything that maybe prevents your production code from running in a unit test setup.

    Wrong approach: you are trying to work around a symptom.

    The root cause is most likely that you wrote hard to test production code. The answer is: spend your time and energy to learn how to write easy to test production code. Start with these videos for example.

    You see, any class or method that your production code contains should adhere the single responsibility principle. That alone drives you to production code that contains a minimum number of "external dependencies".

    Beyond that: understand that using static is basically an abnormality in good OOP. Of course, it has its place - but as soon as "X is static" translates into "X breaks my unit tests" you are again, doing something wrong. Any usage of static that breaks your ability to unit test something is a clear indication that you should, again, fix your design.