簡體   English   中英

無法為單元測試自動裝配 RestTemplate

[英]Unable to autowire RestTemplate for unit test

我有一個服務,它使用RestTemplate的自動裝配實例,如下所示

@Service
class SomeAPIService {
    private RestTemplate restTemplate;

    SomeAPIService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        this.restTemplate.setRequestFactory(HttpUtils.getRequestFactory());
    }
}

在非測試環境中一切正常。 但是當我嘗試在測試配置文件中運行以下單元測試時,它開始抱怨無法自動裝配休息模板。

@RunWith( SpringJUnit4ClassRunner.class )
@SpringBootTest(classes = MyApplication.class, webEnvironment = RANDOM_PORT, properties = "management.port:0")
@ActiveProfiles(profiles = "test")
@EmbeddedPostgresInstance(flywaySchema = "db/migration")
public abstract class BaseTest {
}

@SpringBootTest(classes = SomeAPIService.class)
public class SomeAPIServiceTest extends BaseTest {
    @Autowired
    SomeAPIService someAPIService;

    @Test
    public void querySomeAPI() throws Exception {
        String expected = someAPIService.someMethod("someStringParam");
    }
}

以下是詳細的例外情況——

引起:org.springframework.beans.factory.UnsatisfiedDependencyException:創建名為“someAPIService”的bean時出錯:通過構造函數參數0表示的不滿足的依賴; 嵌套異常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:沒有可用的“org.springframework.web.client.RestTemplate”類型的合格 bean:預計至少有 1 個 bean 有資格作為自動裝配候選。 依賴注釋:{}

有什么線索嗎?

以下幫助我自動裝配了正確的依賴項。 解決方案是還將RestTemplate.class包含在提供給SpringBootTest的類列表中。

@SpringBootTest(classes = {RestTemplate.class, SomeAPIService.class})
class SomeAPIService {
    @Autowired
    SomeAPIService someAPIService;

    @Test
    public void querySomeAPI() throws Exception {
        String expected = someAPIService.someMethod("someStringParam");
    }
}

@Emre 的回答對指導我走向最終解決方案很有幫助。

您正在嘗試在不滿足其依賴關系的情況下自動裝配 SomeAPIService。 您應該將 Rest 模板注入 SomeAPIService。 但是您收到了用於 Rest 模板的 NoSuchBeanDefinitionException。

看看如何注入它:

如何使用注釋自動裝配 RestTemplate

替代答案是 - 使用TestRestTemplate

來自官方文檔 >>>

TestRestTemplate可以直接在您的集成測試中實例化,如以下示例所示:

public class MyTest {

    private TestRestTemplate template = new TestRestTemplate();

    @Test
    public void testRequest() throws Exception {
        HttpHeaders headers = this.template.getForEntity(
                "https://myhost.example.com/example", String.class).getHeaders();
        assertThat(headers.getLocation()).hasHost("other.example.com");
    }

}

或者,如果您將@SpringBootTest注釋與WebEnvironment.RANDOM_PORTWebEnvironment.DEFINED_PORT ,您可以注入一個完全配置的TestRestTemplate並開始使用它。 如有必要,可以通過RestTemplateBuilder bean 應用其他自定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM