繁体   English   中英

在spring-boot测试中使用属性文件

[英]Using properties files in spring-boot tests

我有简单的Spring启动Web服务,配置我使用.properties文件。 作为spring-mail配置的示例,我在src/main/resources/config/文件夹中有单独的文件mailing.properties

在主应用程序中我使用以下方法包括

@PropertySource(value = { "config/mailing.properties" })

问题出现在测试中,我想使用此文件中的相同属性,但是当我尝试使用它时,我得到fileNotFaundExeption

问题是:

  • 我应该在我的src/test文件夹中有单独的资源,还是可以从src/main文件夹访问资源,如果有,怎么办?

UPDATE增加了消息来源

考试类:

    @RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource("classpath:config/mailing.properties")
public class DemoApplicationTests {

    @Autowired
    private TestService testService;

    @Test
    public void contextLoads() {
        testService.printing();
    }

}

服务类:

    @Service
public class TestService
{
    @Value("${str.pt}")
    private int pt;

    public void printing()
    {
        System.out.println(pt);
    }
}

主app类:

@SpringBootApplication
@PropertySource(value = { "config/mailing.properties" })
public class DemoApplication {

    public static void main(String[] args)
    {
        SpringApplication.run(DemoApplication.class, args);
    }
}

结构体

您可以在测试类中使用@TestPropertySource批注。

例如,您的mailing.properties文件中有此属性:

mailFrom=fromMe@mail.com

只需在测试类上注释@TestPropertySource("classpath:config/mailing.properties")

您应该能够使用@Value注释读取属性。

@Value("${fromMail}")
private String fromMail;

为避免在多个测试类上注释此注释,您可以实现超类或元注释


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);
    }
}

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM