[英]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。
看看如何注入它:
替代答案是 - 使用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_PORT
或WebEnvironment.DEFINED_PORT
,您可以注入一个完全配置的TestRestTemplate
并开始使用它。 如有必要,可以通过RestTemplateBuilder
bean 应用其他自定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.