Mocking @Value
About
What is @Value?
@Value?@Value("${scope.stepup.otp}")
private String stepUpOtpScope;Unit Testing (No Spring Context)
1. Set the Field via Reflection (Private Fields)
public class MyService {
@Value("${scope.stepup.otp}")
private String stepUpOtpScope;
public String getScope() {
return stepUpOtpScope;
}
}2. Use a Constructor or Setter (Public Fields or Refactored Code)
Option 1: Use @Component + @Value on Constructor Parameter
@Component + @Value on Constructor ParameterOption 2: Use @Bean Method in Configuration Class
@Bean Method in Configuration ClassIntegration Testing (Using Spring Context)
1. Use @TestPropertySource or Spring Profiles
@TestPropertySource or Spring Profiles2. Use @DynamicPropertySource (for dynamic values or Testcontainers)
@DynamicPropertySource (for dynamic values or Testcontainers)Last updated