Search code examples
javaspringunit-testingjunit

How to write junit for a class having private fields?


I have a class which is used for email validation. The class has two private String fields out of which i have injected the value of one from application.properties.

public class EmailValidation {

    private final String someString = "xyz"

    @Value("${regex}")
    private String emailRegex;

    // methods
}


public class EmailValidaitonTest {

   private final EmailValidation obj = new EmailValidation();

   //missing emailRegex
}

Now i have to write a unit test for this. This class has no dependency, so i just decided to use the new operator in EmailValidationTest class for the class object. Now, i can access the String someString but i cannot have the value of emailRegex since it was injected by Spring. How can i set its value in the test class and i want its value to be same as in my application.properties.


Solution

  • You use ReflectionTestUtils.setField to inject property value in test cases.

     public class EmailValidationTest{
         private @InjectMocks EmailValidation validation; 
         private String emailRegexPattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$";
        
         @BeforeAll
         public void setUp(){
            ReflectionTestUtils.setField(validation, "emailRegex", emailRegexPattern);
         }
        
        //your test cases here.
        }