无法自动连接RestTemplate进行单元测试

com*_*tor 0 java junit mockito spring-boot

我有一个使用的自动装配Autowired实例的服务RestTemplate下面像

@Service
class SomeAPIService {
    private RestTemplate restTemplate;

    SomeAPIService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        this.restTemplate.setRequestFactory(HttpUtils.getRequestFactory());
    }
}
Run Code Online (Sandbox Code Playgroud)

在非测试环境中一切正常。但是,当我尝试在测试配置文件中运行以下单元测试时,它开始抱怨无法自动连接其余模板。

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是详细的例外情况-

由以下原因引起:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“ someAPIService”的bean时出错:通过构造函数参数0表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型为“ org.springframework.web.client.RestTemplate”的合格bean:期望至少有1个合格为自动装配候选的bean。依赖注释:{}

有什么线索吗?

com*_*tor 5

以下帮助我自动连接了正确的依赖项。解决方案还应包括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");
    }
}
Run Code Online (Sandbox Code Playgroud)

@Emre答案有助于指导我寻求最终解决方案。