I have some variables defined in application-local.yml in my spring boot project and these variables are used in many of the services by using @Value annotation. Now while trying to unit test these services, the service is unable to retrieve the value of the variable from the application-local.yml and instead is throwing NullPointer Exception. What should I do?
application-local.yml :
variables:
maxVal: 24
Service.java
@Value("${variables.maxVal:24}")
public Integer maxima;
FunctionA()
{
return maxima 1;
}
Unit Test
@Test
testFunctionA()
{
assert.assertEquals(25,FunctionA())
}
CodePudding user response:
your properties file is not being loaded. the proper manner for test properties is to use a application-test.yaml, located under test/resources, it will be automatically loaded when you run your tests.
CodePudding user response:
You can injecting the property in the context with Spring Boot in this simple way thanks to the properties attribute of @SpringBootTest :
@SpringBootTest(properties="property.value=dummyValue")
public class FooTest{
@Autowired
Foo foo;
@Test
public void doThat(){
...
}
}
You could use as alternative @TestPropertySource but it adds an additional annotation :
@SpringBootTest
@TestPropertySource(properties="property.value=dummyValue")
public class FooTest{ ...}
With Spring (without Spring Boot), it should be a little more complicated but as I didn't use Spring without Spring Boot from a long time I don't prefer say a stupid thing.
As a side note : if you have many @Value fields to set, extracting them into a class annotated with @ConfigurationProperties is more relevant because we don't want a constructor with too many arguments.
Hope thats helped .