PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 19, 2022

[FIXED] How to fix environment.getActiveProfiles() is null in UnitTest Java

 August 19, 2022     environment-variables, java, junit, spring, unit-testing     No comments   

Issue

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 ?


Solution

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);.



Answered By - ZeroOne
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing