2012-05-25 45 views
2

我正在使用新的Spring配置創建項目。我有一個基類,它擁有幾個屬性:對Spring配置的正確繼承

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {Basic.class, Protected.class}) 
public class BaseTest { 
    @Autowired(required = false) protected String userName; 
    @Autowired(required = false) protected String password; 
    @Autowired protected String baseURL; 

    @Test 
    public void outputData() { 
    System.out.println("UserName: " + userName + " Password: " 
         + password + "Base URL: " + baseURL); 
    } 
} 

@ActiveProfiles("default,protected") 
public abstract class ProtectedTest extends BaseTest 
{ 
    @Autowired protected String userName; 
    @Autowired protected String password; 
} 

@Configuration @Profile("default") 
public class Basic { 
    @Bean public String baseURL() { return "http://www.baseURL.com"; } 
} 

@Configuration @Profile("protected") 
public class Protected { 
    @Bean public String userName() { return "userName"; } 
    @Bean public String password() { return "password"; } 
} 

然而,當我去跑我保護的測試中,我收到基URL不正確接線的通知。由於它擴展了BaseTest,並且兩個配置文件都處於活動狀態,爲什麼我沒有收到baseURL bean?

回答

1

它必須@ActiveProfiles({"default","protected"}),在你的情況下,它會假設按名稱default, protected輪廓是積極的,不是defaultprotected

一件事是在基類註釋BaseTest不被ProtectedTest衍生,所以您將需要再次將@RunWith@ContextConfiguration用於測試運行

+1

這已經過了漫長的一天,我剛剛從我的環境變量配置中複製了它。但是有兩點需要注意:您不必在[擴展類](http://junit.sourceforge.net/javadoc/org/junit/runner/RunWith.html)或ContextConfigurations [他們默認繼承](http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/test/context/ContextConfiguration.html#inheritLocations()) – Scott