Home > database >  How to fix environment.getActiveProfiles() is null in UnitTest Java
How to fix environment.getActiveProfiles() is null in UnitTest Java

Time:08-09

I have a piece of Java code which uses an environment variable and the behaviour of the code depends on the value of this variable. And then I created the UnitTest of it in TestClass and debug to see the result.

Then I found null from environment.getActiveProfiles()

enter image description here

I set the environment in serviceImpl by this way

@Autowired
private Environment environment;

I've already mocked some environment here in TestClass

@Mock
private Environment environment; 
...
...
String[] activeProfiles =  new String[]{"dev"};
ActiveProfilesResponse activeProfilesResponse = new ActiveProfilesResponse();
activeProfilesResponse.setProfiles(List.of(activeProfiles));
when(environment.getActiveProfiles()).thenReturn(activeProfiles);

and also provides @ActiveProfiles("dev") in that TestClass

Do I need to add any mock or anything else for it ?

CodePudding user response:

Your environment is null, hence the NullPointerException. This means that your mocked Environment from the test class is not injected into your test subject class. You haven't shown us the part of your class where environment is supposed to be set. But, for example, if it is injected in the constructor, make sure your test class initializes your class with new YourClass(environment); and not new YourClass(null);.

  • Related