我正在嘗試使用 Mockito 進行一些 junit 測驗以在 SprinBoot 應用程式中作業。
application.properties現在我的服務有一些變數是通過@Value注釋填充的:
@Component
@Slf4j
public class FeatureFlagService {
@Autowired
RestTemplate restTemplate;
@Value("${url.feature_flags}")
String URL_FEATURE_FLAGS;
// do stuff
}
我正在嘗試使用TestPropertySource這樣的方法來測驗它:
@ExtendWith(MockitoExtension.class)
@TestPropertySource(properties = { "${url.feature_flags} = http://endpoint" })
class FeatureFlagServiceTests {
@Mock
RestTemplate restTemplate;
@InjectMocks
FeatureFlagService featureFlasgService;
@Test
void propertyTest(){
Assertions.assertEquals(featureFlasgService.URL_FEATURE_FLAGS, "http://endpoint");
}
然而,該屬性沒有被填滿并且仍然存在null。
有很多關于此的主題,但我無法拼湊出一個解決方案。我看到了建議的解決方案@SpringBootTest,但隨后似乎想要進行集成測驗,啟動服務,但由于無法連接到資料庫而失敗。所以這不是我要找的。
我還看到了建議我制作PropertySourcesPlaceholderConfigurerbean 的解決方案。我嘗試通過放置:
@Bean
public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
return new PropertySourcesPlaceholderConfigurer();
}
在我的Application.java. 但這不起作用/還不夠。我不確定我是否應該這樣做,或者是否還有更多我不知道的地方。
請指教。
uj5u.com熱心網友回復:
您可以@SpringBootTest通過將包含 的類傳遞給它而不運行整個應用程式來使用它,@Value但是您必須使用@ExtendWith({SpringExtension.class})包含在其中的Spring 的擴展,并且@SpringBootTest使用 Spring 的MockBean而不是像這樣自動裝配 bean:@Mock@Autowired
@SpringBootTest(classes = FeatureFlagService.class)
class FeatureFlagServiceTests {
@MockBean
RestTemplate restTemplate;
@Autowired
FeatureFlagService featureFlasgService;
@Test
void propertyTest(){
Assertions.assertEquals(featureFlasgService.URL_FEATURE_FLAGS, "http://endpoint");
}
uj5u.com熱心網友回復:
我建議您嘗試這種方法。只需要稍微重構并添加一個包私有建構式到你的FeatureFlagService.
FeatureFlagService.java
@Component
@Slf4j
public class FeatureFlagService {
private final RestTemplate restTemplate;
private final String URL_FEATURE_FLAGS;
// package-private constructor. test-only
FeatureFlagService(RestTemplate restTemplate, @Value("${url.feature_flags}") String flag) {
this.restTemplate = restTemplate;
this.URL_FEATURE_FLAGS = flag;
}
// do stuff
}
然后準備你的 mocks 和 url,并通過constructor-injection.
FeatureFlagServiceTests.java
public class FeatureFlagServiceTests {
private FeatureFlagService featureFlagService;
@Before
public void setup() {
RestTemplate restTemplate = mock(RestTemplate.class);
// when(restTemplate)...then...
String URL_FEATURE_FLAGS = "http://endpoint";
featureFlagService = new FeatureFlagService(restTemplate, URL_FEATURE_FLAGS);
}
@Test
public void propertyTest(){
Assertions.assertEquals(featureFlasgService.getUrlFeatureFlags(),
"http://endpoint");
}
}
顯著的優勢是,您FeatureFlagServiceTests變得非常易于閱讀和測驗。您不再需要 Mockito 的魔術注釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/463837.html
