0

I am using Spring and Java 11. I used non-static fields in my @Service, but I got a critical error on Sonar Qube saying:

"Members of Spring components should be injected"

So I changed these fields to static.

Now in my unit tests, I test my service, which is declared in this way:

@InjectMocks
@Spy
private myService myService;

But if I change a static field in one test, the value is reflected in the other test. How can I set all private static fields on values which are initialized on start:

private static Integer count = 1;
private static boolean isChecked = true;

Edit: I can add to my class I have also filed it with annotation @Autowired

@Autowired
private MySecondService mySecondService;

in test class, I have this object with annotation @Mock

@Mock
private MySecondService mySecondService;

So if a solution will be to use @Before or something like this and initialize this object in this method. I also need to initialize all Mock objects.

Reg
  • 10,717
  • 6
  • 37
  • 54
Silny ToJa
  • 1,815
  • 1
  • 6
  • 20
  • regression to the rescue. https://stackoverflow.com/questions/14102000/cannot-change-static-final-field-using-java-reflection – Stultuske Nov 24 '22 at 08:41
  • @Stultuske that is about static and final. This field is only static and not final. So compiler won't inline it. – Aqeel Ashiq Nov 24 '22 at 08:44
  • Never ever do something like _InjectMocks_ with _Spy_. It is not supported by Mockito, on the contrary Mockito discourages this combination. – Michael Katt Nov 24 '22 at 08:50
  • What about creating setter methods and marking them @VisibleForTesting? Sonar will give an alert if these methods are called outside tests. – dimirsen Z Nov 24 '22 at 08:51
  • @dimirsenZ I don't like this solution where I have to create a public method to be able to test something. But If I don't find other solution maybe I will do it. – Silny ToJa Nov 24 '22 at 08:56
  • The problem is not the static, but the fcat you are keeping state in your singelton service. Unless that is really needed on the class/instance level yu should inline the variables in the methods where needed. – M. Deinum Nov 24 '22 at 09:48

0 Answers0