2 回答

TA貢獻1860條經驗 獲得超8個贊
這是因為在執行 REST 調用時,實例未通過 注入。您需要在組件類中聲明 的方法,該方法在應用程序啟動期間或換句話說,在組件掃描期間進行掃描。從而可用于 .RestTemplate
Spring IOC
getRestTemplate
restTemplate
autowire

TA貢獻2021條經驗 獲得超8個贊
按照@chrylis建議將配置與控制器分離后,您可以像這樣繼續操作。
您必須嘗試模擬 RequestEntity.post 方法。請注意,它是一個靜態方法,其模擬方式與通常的公共實例方法略有不同。為此,您需要使用PowerMockito,因為Mockito不會這樣做。
在 pom 中添加依賴項,如下所示:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>
然后用 注釋測試類,如下所示:@RunWith@PrepareForTest
@RunWith(PowerMockRunner.class)
@PrepareForTest({RequestEntity.class})
public class TestClass {
}
和模擬 post 方法,如下所示:
PowerMockito.mockStatic(RequestEntity.class); when(RequestEntity.post(any(URI.class))).thenReturn(getRequestEntityResponseBody());
private RequestEntity< CustomerInfo > getRequestEntityResponseBody(){
//code
}
更新
CustomerInfo customerInfo = new CustomerInfo();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
RequestEntity<CustomerInfo> customerInfoRequestEntity = new ResponseEntity<CustomerInfo>(customerInfo, responseHeaders, HttpStatus.OK);
PowerMockito.mockStatic(RequestEntity.class);
when(RequestEntity.post(any(URI.class))).thenReturn(customerInfoRequestEntity);
添加回答
舉報