更新
正如斯蒂芬在註釋中提到的物業內聯下面展示了通過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 {
}
這將有助於確切知道你想要完成什麼。最好簡單地爲該測試設置一個'@ Configuration'類,它無條件地聲明'@Bean MyService'。 – chrylis
這種方法看起來很有趣。我如何在MyServiceTest中執行特定的配置? –
我不確定新的Boot測試魔法是如何工作的;我通常使用'@ ContextConfiguration'。你可以嘗試在你的測試類中聲明一個(靜態)'@ Configuration'嵌套類,看看它是否被拾取。 – chrylis