【发布时间】:2020-06-21 08:49:45
【问题描述】:
我有一个使用RestTemplate 的简单服务类。我正在使用 @RestClientTest 对其进行测试,并希望只初始化所需的服务 bean
@SpringBootApplication
class DemoApplication {
@Bean fun restTemplate() = RestTemplateBuilder().build()
@Bean fun xyzService() = XyzService()
}
@Service
class MyServiceImpl(private val restTemplate: RestTemplate): MyService {
override fun fetch(id: String) {
print(restTemplate.getForObject(URI("http://localhost:9090"), String::class.java))
}
}
@RestClientTest(MyServiceImpl::class)
@AutoConfigureWebClient(registerRestTemplate = true)
class MyServiceTest {
@Autowired
private lateinit var mockServer: MockRestServiceServer
@Autowired
private lateinit var myService: MyService
@Test
fun test(){
mockServer.expect(ExpectedCount.once(), MockRestRequestMatchers.requestTo(URI("http://localhost:9090")))
.andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
.andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body("hello world"))
myService.fetch("123")
}
}
我想在测试中排除DemoApplication,只测试服务类的bean。问题是 xyzService 的 bean 初始化失败(它依赖于 RabbitTemplate),我不想用 mocks 搞乱测试代码。
【问题讨论】:
标签: spring-boot unit-testing kotlin spring-test junit5