I would like to learn how to write a SpringBootTest for an existing ApplicationConfiguration class for the purpose of testing the functionality of reading the application.yml file. I would be happy with java or groovy. I am not able to share the existing ApplicationConfiguration class, so I would gladly accept any example offered that starts with an existing ApplicationConfiguration that reads in an application.yml file and parses data in that file over to the objects that need to receive the configurations.
To date, what I have read so far hasn't helped me understand how to do this and I am here with my hat in my hand asking for some help. I get some of the basic concepts of Spring Boot and Spring Boot Testing, but actually hooking it up from scratch to accomplish this specific task is making it clear to me that I am missing something important in the approach to how to do this.
If you want to take the time to explain it to me that's great, but I certainly don't expect you to walk a Spring Boot Newbie through this stuff if you have seen documentation online, tutorials, or even videos that would be appropriate for this challenge.
To date, the resources I have found haven't filled in that missing gap that would let me go from an existing ApplicationConfiguration class to making a new ApplicationConfigurationTests class from it. The Spring Documentation itself sure seems to gloss over some things like: minimal requirements.
CodePudding user response:
I suppose you have application.yml
.
For example, you defined some properties of the message queue system.
mq:
receive_channel: "RES"
send_channel: "REQ"
First of all, you should define a class that presents the related values that you placed in your .yml
file.
public class MQProperties {
private String receive_channel;
private String send_channel;
// getter and setters
}
Second, you should define a configuration class as below.
@Configuration
@PropertySource(value = "classpath:application.yml")
public class ApplicationConfigurationProperties {
@Bean
@ConfigurationProperties(prefix = "mq")
public MQProperties mqProperties() {
return new MQProperties();
}
}
Finally in your test class you validate the value of properties.
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {
@Value("${mq.receive_channel}")
private String mqReceiveChannel;
@Value("${mq.send_channel}")
private String mqSendChannel;
@Autowired
private ApplicationConfigurationProperties configurationProperties;
@Test
public void get_mq_receive_channel() {
assertThat(configurationProperties.mqProperties().getReceive_channel()).isEqualTo(mqReceiveChannel);
}
@Test
public void get_mq_send_channel() {
assertThat(configurationProperties.mqProperties().getSend_channel()).isEqualTo(mqSendChannel);
}
}