我有一個使用 Mockito 進行注釋和測驗@Spy的測驗類。@InjectMocks被測類具有從application.properties檔案中檢索的值 (url)。我想測驗這個 url 是否在使用它的方法中正確設定。如果我洗掉@Spyand@InjectMocks注釋并使用@Autowireand ,我可以做到這一點@SpringBootTest。但是,這會破壞使用 spy 功能的其他測驗,所以我只是想知道是否有任何方法可以保持 spy 作業并在同一個檔案中測驗我們所有的方法,也許不需要引入@SpringBootTest注釋和自動裝配?我們現在使用的解決方法是有兩個檔案,一個使用間諜,另一個測驗使用屬性檔案的特定方法,并且需要加載完整的背景關系,但不確定這是最好的解決方案?
這是對間諜的測驗:
@ExtendWith(MockitoExtension.class)
class ProviderHelperServiceTest {
@Spy
@InjectMocks
ProviderHelperService providerHelperService;
@Value("${viaduct-url}")
String viaductUrl;
@Test
void testGetRequestBodyUriSpec() {
WebClient.RequestBodyUriSpec requestBodyUriSpec = providerHelperService.getRequestBodyUriSpec("sifToken");
final String[] url = new String[1];
requestBodyUriSpec.attributes(httpHeaders -> {
url[0] = (String) httpHeaders.get("org.springframework.web.reactive.function.client.WebClient.uriTemplate");
});
// Fails as url[0] comes back as null. Disabled and moved to another file.
assertEquals(viaductUrl, url[0]);
}
@SpringBootTest
class ProviderHelperService2Test {
@Autowired
ProviderHelperService providerHelperService;
@Value("${viaduct-url}")
String viaductUrl;
@Test
void testGetRequestBodyUriSpec() {
WebClient.RequestBodyUriSpec requestBodyUriSpec = providerHelperService.getRequestBodyUriSpec("sifToken");
final String[] url = new String[1];
requestBodyUriSpec.attributes(httpHeaders -> {
url[0] = (String) httpHeaders.get("org.springframework.web.reactive.function.client.WebClient.uriTemplate");
});
assertEquals(viaductUrl, url[0]);
}
}
這是正在測驗的方法:
public class ProviderHelperService {
@Value("${viaduct-url}")
String viaductUrl;
public WebClient.RequestBodyUriSpec getRequestBodyUriSpec(String sifToken) {
WebClient.RequestBodyUriSpec requestBodyUriSpec = WebClient.create().post();
requestBodyUriSpec.header("Authorization", sifToken);
requestBodyUriSpec.uri(viaductUrl);
return requestBodyUriSpec;
}
}
uj5u.com熱心網友回復:
執行此類測驗的最簡潔方法是將欄位注入替換為建構式注入,然后您可以很容易地確認傳遞給類的值是否從服務呼叫中回傳。
如果您使用的是 Boot,通常最好將使用替換@Value為@ConfigurationProperties. 根據具體情況,您可以將整個屬性物件傳遞給服務的建構式,或者撰寫一個@Bean配置方法來解包相關屬性并將它們作為普通建構式引數傳遞給new.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477576.html
