I have simple spring boot web service, where for configuration I use .properties
files. As example for spring-mail configuration, I have separate file mailing.properties
located in src/main/resources/config/
folder.
in main application I include it using:
@PropertySource(value = { "config/mailing.properties" })
The problem appears when it comes to tests, I would like to use the same properties from this file, but when i try to use it, I get fileNotFaundExeption
.
Question is:
src/test
folder, or it is possible to access resources from src/main
folder, if yes, how?UPDATE added sources
test class:
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource("classpath:config/mailing.properties")
public class DemoApplicationTests {
@Autowired
private TestService testService;
@Test
public void contextLoads() {
testService.printing();
}
}
service class:
@Service
public class TestService
{
@Value("${str.pt}")
private int pt;
public void printing()
{
System.out.println(pt);
}
}
main app class:
@SpringBootApplication
@PropertySource(value = { "config/mailing.properties" })
public class DemoApplication {
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
}
}
You can use @TestPropertySource
annotation in your test class.
For example you have this attribute in your mailing.properties
file:
Just annotate @TestPropertySource("classpath:config/mailing.properties")
on your test class.
You should be able to read out the property for example with the @Value
annotation.
@Value("${fromMail}")
private String fromMail;
To avoid annotate this annotation on multiple test classes you can implement a superclass or meta-annotations.
EDIT1:
@SpringBootApplication
@PropertySource("classpath:config/mailing.properties")
public class DemoApplication implements CommandLineRunner {
@Autowired
private MailService mailService;
public static void main(String[] args) throws Exception {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... arg0) throws Exception {
String s = mailService.getMailFrom();
System.out.println(s);
}
MailService:
@Service
public class MailService {
@Value("${mailFrom}")
private String mailFrom;
public String getMailFrom() {
return mailFrom;
}
public void setMailFrom(String mailFrom) {
this.mailFrom = mailFrom;
}
}
DemoTestFile:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
@TestPropertySource("classpath:config/mailing.properties")
public class DemoApplicationTests {
@Autowired
MailService mailService;
@Test
public void contextLoads() {
String s = mailService.getMailFrom();
System.out.println(s);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With