Can I drown methods invoked by reflection using Mockito?

I am trying to write unit tests for my code that uses reflection to call hidden methods on an object that I want to stub for my test:

methodUnderTest(Arg argument) { Method toCall = Arg.class.getMethod("toCall"); Object val = toCall.invoke(argument); // Do stuff with val... } 

Is it possible to create an Arg layout that I can pass to this method that will allow me to drown out the call toCall ()?

Arg is not an object that I create, so I cannot change the availability of its methods.

+4
source share
1 answer

yes, you can drown out methods called with reflection. but you cannot close the private method - mockito just does not have syntax for it. you also cannot drown out final methods, static methods, fields and classes. for such a hack you will need powermockito.

but you should not use it. reorganize! split methodUnderTest into two (or three) methods. the most important one will get Object val as input and make your business logic. you should check this method.

the second method will prepare the method and parameters for the call (and, ultimately, its call). you are currently accessing a static field in this part. not. use different methods whenever possible (as Colin suggested). if there is some complicated logic, then check this logic, but you do not have the invoke test method - it works, the guys from sun / oracle have already tested it

0
source

Source: https://habr.com/ru/post/1492172/


All Articles