Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock @Value in SpringBoot unit test not working

I am trying to get some junit tests with Mockito to work in a SprinBoot application.

Now my Service has some variable that gets filled from the application.properties by means of @Value annotation:

@Component
@Slf4j
public class FeatureFlagService {

  @Autowired
  RestTemplate restTemplate;

  @Value("${url.feature_flags}")
  String URL_FEATURE_FLAGS;

// do stuff
}

I am trying to test this by using TestPropertySource like so:

@ExtendWith(MockitoExtension.class)
@TestPropertySource(properties = { "${url.feature_flags} = http://endpoint" })
class FeatureFlagServiceTests {

  @Mock
  RestTemplate restTemplate;

  @InjectMocks
  FeatureFlagService featureFlasgService;

  @Test
  void propertyTest(){
    Assertions.assertEquals(featureFlasgService.URL_FEATURE_FLAGS, "http://endpoint");
  }

However the property does not get filled and remains null.

There are a bunch of tpoics on this, but I have not been able to piece together a solution. I saw solutions suggesting @SpringBootTest, but then it seems to want to do an integration test, spinning up the service, which fails because it can not connect to DB. So that is not what I am looking for.

I also saw solutions suggesting I make a PropertySourcesPlaceholderConfigurer bean. I tried that by putting :

  @Bean
    public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
    return new PropertySourcesPlaceholderConfigurer();
  }

In my Application.java. But that is not working / not enough. I am not sure if I was supposed to do that differently, or if there is more there that I do not know.

Please advice.

like image 860
Chai Avatar asked Nov 01 '25 06:11

Chai


1 Answers

You can use @SpringBootTest without running the whole application by passing it the class that contains the @Value but you have to use Spring's extension @ExtendWith({SpringExtension.class}) which is included inside @SpringBootTest and by that using Spring's MockBean instead of @Mock and @Autowired for autowiring the bean like this:

@SpringBootTest(classes = FeatureFlagService.class)
class FeatureFlagServiceTests {

  @MockBean
  RestTemplate restTemplate;

  @Autowired
  FeatureFlagService featureFlasgService;

  @Test
  void propertyTest(){
    Assertions.assertEquals(featureFlasgService.URL_FEATURE_FLAGS, "http://endpoint");
  }
like image 81
Bahij.Mik Avatar answered Nov 03 '25 20:11

Bahij.Mik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!