【发布时间】:2018-09-17 20:02:24
【问题描述】:
我有一个服务,它使用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 个符合 autowire 条件的 bean 候选人。依赖注释:{}
有什么线索吗?
【问题讨论】:
标签: java spring-boot junit mockito