2016-10-03 71 views
2

我有簡單的spring啓動web服務,其中配置使用.properties文件。作爲彈簧郵件配置的示例,我有單獨的文件mailing.properties位於src/main/resources/config/文件夾中。在spring-boot測試中使用屬性文件

在主要應用

我包括它使用:

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

主要的應用程序的類:

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

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

structure

回答

3

您可以在測試類中使用@TestPropertySource註釋。

比如你有這樣的屬性,在mailing.properties文件:

[email protected]

在您的測試類只是標註@TestPropertySource("classpath:config/mailing.properties")

您應該能夠讀出屬性,例如@Value註釋。

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

要避免在多個測試類上註釋此註釋,您可以實現超類或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); 
    } 
} 

enter image description here

+0

但文件'.properties'可以保留在src/main/resources中''不需要創建'src/test/resources ...'? – Bublik

+0

是的,正確的。我想你的配置就像這個'src/main/resources/config/mailing.properties'。如果是的話,它應該工作 – Patrick

+0

仍然會得到:'由於:java.io.FileNotFoundException異常:無法打開ServletContext資源[/config/mailing.properties]'也添加了簡單的來源,我測試了你的溶劑 – Bublik