简体   繁体   English

无法为单元测试自动装配 RestTemplate

[英]Unable to autowire RestTemplate for unit test

I have a service which uses an autowired instance of RestTemplate like below我有一个服务,它使用RestTemplate的自动装配实例,如下所示

@Service
class SomeAPIService {
    private RestTemplate restTemplate;

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

Everything runs fine in non-test environment.在非测试环境中一切正常。 But when I try to run following unit test in test profile, it starts complaining about unable to autowire rest template.但是当我尝试在测试配置文件中运行以下单元测试时,它开始抱怨无法自动装配休息模板。

@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");
    }
}

Following is the detailed exception -以下是详细的例外情况——

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'someAPIService': Unsatisfied dependency expressed through constructor parameter 0;引起:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“someAPIService”的bean时出错:通过构造函数参数0表示的不满足的依赖; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestTemplate' available: expected at least 1 bean which qualifies as autowire candidate.嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“org.springframework.web.client.RestTemplate”类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选。 Dependency annotations: {}依赖注释:{}

Any clues?有什么线索吗?

Following helped me get the correct dependencies autowired.以下帮助我自动装配了正确的依赖项。 The solution is to also include RestTemplate.class in list of classes given to SpringBootTest .解决方案是还将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 answer was helpful in guiding me towards the final solution. @Emre 的回答对指导我走向最终解决方案很有帮助。

You are trying to autowire SomeAPIService without satisfying its dependencies.您正在尝试在不满足其依赖关系的情况下自动装配 SomeAPIService。 You should inject Rest Template to SomeAPIService.您应该将 Rest 模板注入 SomeAPIService。 But you are getting NoSuchBeanDefinitionException for Rest Template.但是您收到了用于 Rest 模板的 NoSuchBeanDefinitionException。

Take a look how to inject it :看看如何注入它:

How to autowire RestTemplate using annotations 如何使用注释自动装配 RestTemplate

Alternative answer would be - to use TestRestTemplate替代答案是 - 使用TestRestTemplate

From official docs >>> 来自官方文档 >>>

TestRestTemplate can be instantiated directly in your integration tests, as shown in the following example: 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");
    }

}

Alternatively, if you use the @SpringBootTest annotation with WebEnvironment.RANDOM_PORT or WebEnvironment.DEFINED_PORT , you can inject a fully configured TestRestTemplate and start using it.或者,如果您将@SpringBootTest注释与WebEnvironment.RANDOM_PORTWebEnvironment.DEFINED_PORT ,您可以注入一个完全配置的TestRestTemplate并开始使用它。 If necessary, additional customizations can be applied through the RestTemplateBuilder bean.如有必要,可以通过RestTemplateBuilder bean 应用其他自定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM