0

I'm using Mockito (3.6.x) for my unit tests in Spring Boot (2.4.x) with JUnit 4. There are unit tests where I need to mock final classes (e.g. java.lang.reflect.Method), and there are other unit tests where I need to mock common interfaces (e.g. org.springframework.core.env.Environment).

I have tried many solutions but none have worked for me. I found this article where I can mock final classes, but when I add the mock-inline-maker plugin, only unit tests that mock final classes work (classes in which I mock java.lang.reflect.Method) and the others crash (classes in which I mock org.springframework.core.env.Environment), and vice versa when I remove the mock-inline-maker.

Is there a way to configure the mock-inline-maker for some classes in the test and not for others?

P.S. The only reason to mock final classes is to achieve this code block in my unit tests:

MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = signature.getMethod();
CustomAnnotation customAnnotation = method.getAnnotation(CustomAnnotation.class);

I thank you all very much.

  • Why do you want to mock `Method` and `Environment`? They arent `static final` objects... just create new instances for your test cases, assuming the actual code uses them. – j1mbl3s Jun 05 '21 at 03:21
  • Actually yes, ```Method``` is a final class according to [Java docs](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html), and Mockito throws an error when I try to mock/stub final classes. – Kevin Riaño Jun 05 '21 at 21:13
  • I mean that you can create an instance of `Method`/`Environment` set up in a way to test your code, not that you can necessarily extend them. – j1mbl3s Jun 05 '21 at 21:17
  • @j1mbl3s How can I do that? I tried to create an instance of ```Method``` but I could not, Java did not let me since ```Method``` is a final class. – Kevin Riaño Jun 08 '21 at 13:16
  • [`Class.getMethods()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getMethods()) returns a `Method[]` array. Create a class with some methods that you want to test your functionality with. – j1mbl3s Jun 09 '21 at 07:13
  • OK, I have already done this, but my code now throws a vulnerability of kind Broken Access Control in my quality scans. I read about this on [Oracle](https://www.oracle.com/java/technologies/javase/seccodeguide.html#9). I can not let my code with this issue. Please, do you have another idea? – Kevin Riaño Jun 10 '21 at 17:29
  • A BAC sounds like another issue entirely... – j1mbl3s Jun 11 '21 at 08:29
  • Ok @j1mbl3s, thanks for your help!, I will make another question, using PowerMockito this time. – Kevin Riaño Jun 17 '21 at 23:07

0 Answers0