2016-12-14 71 views
1

我正在使用Spring Boot 1.4.2。用@ConditionaOnProperty註解的類的Spring和web集成測試

我有一個服務註解如下

@Service 
@ConditionalOnProperty("${my.property.enabled:false}") 
public class MyService { 

} 

,我想測試它做一個集成測試,例如

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT) 
public class MyServiceTest { 

    @Autowired 
    private MyService myService; 

} 

服務在測試中不是自動裝配的。我想避免在測試文件夾內的屬性文件中設置屬性。我不能直接通過MyServiceTest內的這種註釋來啓用該屬性嗎?

+0

這將有助於確切知道你想要完成什麼。最好簡單地爲該測試設置一個'@ Configuration'類,它無條件地聲明'@Bean MyService'。 – chrylis

+0

這種方法看起來很有趣。我如何在MyServiceTest中執行特定的配置? –

+0

我不確定新的Boot測試魔法是如何工作的;我通常使用'@ ContextConfiguration'。你可以嘗試在你的測試類中聲明一個(靜態)'@ Configuration'嵌套類,看看它是否被拾取。 – chrylis

回答

1

更新

正如斯蒂芬在註釋中提到的物業內聯下面展示了通過properties參數在@SpringBootTest直接可能發生測試目的,在這種情況下你不需要的@TestPropertySource

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, 
       properties = { "my.property.enabled = true" }) 
public class MyServiceTest { 

    @Autowired 
    private MyService myService; 

} 

原來的答案

您可以直接使用@TestPropertySource內嵌在您的測試配置類所需要的屬性:

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT) 
@TestPropertySource(properties = { "my.property.enabled = true" }) 
public class MyServiceTest { 

    @Autowired 
    private MyService myService; 

} 

還要注意,註釋爲你定義它不會工作,也許你的意思是使用在這種情況下@ConditionalOnExpression它的工作:

@Service 
@ConditionalOnExpression("${my.property.enabled:false}") 
public class MyService { 

} 

@ConditionalOnProperty是更具表現力和你的情況可以寫爲:

@Service 
@ConditionalOnProperty(prefix="my.property" , name = "enabled", havingValue = "true") 
public class MyService { 

} 
+2

也許你可以更新你的答案,提到'SpringBootTest'有一個'properties'快捷方式。所以它會像'@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,properties =「」my.property.enabled = true「)' –

+0

謝謝Stephane,我會更新我的答案。 – dimitrisli