我按照许多博客的分步说明使用 MockK 实现模拟:
class SWServiceImplTest {
@MockK
lateinit var externalApi: ExternalApiService
@InjectMockKs
lateinit var SWService: SWServiceImpl
@Before
fun setUp() = MockKAnnotations.init(this)
@Test
fun SWCharacterReturnsCorrectValues() {
every { externalApi.get<Characters>(Utils.SW_API) } returns mockCharacters()
val result = SWService.swCharacter!!
assertEquals("blue", result.first().color?.toLowerCase())
assertEquals(result.size, 3)
}
}
我想注入externalApi
我的 SWService
服务并模拟get
注入对象(externalApi
)的方法,但似乎忽略了模拟。
日志:
15:09:54.497 [main] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for <error "java.lang.NoClassDefFoundError: kotlin/coroutines/intrinsics/IntrinsicsKt"> name=externalApi#1
15:09:56.820 [main] DEBUG org.springframework.web.client.RestTemplate - HTTP GET https://xxx.xxx/
15:09:57.038 [main] DEBUG org.springframework.web.client.RestTemplate - Accept=[application/json, application/*+json]
org.springframework.web.client.RestClientException: No HttpMessageConverter for java.lang.Object and content type ""
在我的SWService
文件中,externalApi
在伴随对象中初始化:
companion object{
val api = ExternalApiService()
}
我的实施有问题吗?谢谢