【问题标题】:SpringBoot - Testing services [duplicate]Spring Boot - 测试服务
【发布时间】:2021-03-15 23:07:34
【问题描述】:

我有一个 SpringBoot 应用程序。使用此服务:

@Slf4j
@Service
public class AddressService {

    private final RegionRepository regionRepository;
    private final CommuneRepository communeRepository;
    private final RestTemplate restTemplate;

    public AddressService(RegionRepository regionRepository,
                          CommuneRepository communeRepository,
                          RestTemplate restTemplate) {
        this.regionRepository = regionRepository;
        this.communeRepository = communeRepository;
        this.restTemplate = restTemplate;
    }

    public GeolocationAddress searchFromAddress(String address) {
        // (..)
    }
}

我已经创建了这个测试:

@ExtendWith(SpringExtension.class)
@SpringBootTest
class AddressServiceTest {

    @Autowired
    AddressService addressService;

    @Test
    void searchFromAddress() {
        System.out.println
                (addressService.searchFromAddress("Plaza los Cubos)"));
    }
}

但是当我运行测试时出现这个错误:

***************************
APPLICATION FAILED TO START
***************************

说明:
com.bonansa.service.AddressService 中构造函数的参数 2 需要一个无法找到的 'org.springframework.web.client.RestTemplate' 类型的 bean。

动作:
考虑在你的配置中定义一个 'org.springframework.web.client.RestTemplate' 类型的 bean。

【问题讨论】:

  • 请出示您的 POM/build.gradle。您似乎没有为您自动配置 RestTemplate 的依赖项。

标签: java spring spring-boot spring-mvc junit


【解决方案1】:

Spring Boot 不会自动配置 RestTemplate。所以你不能在没有定义的情况下自动装配 RestTemplate。见https://stackoverflow.com/a/42618428/1992820

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-24
    • 2015-08-02
    • 2020-02-10
    • 1970-01-01
    • 2015-06-24
    • 2017-10-30
    • 2020-08-20
    • 2017-08-01
    相关资源
    最近更新 更多