0

我正在尝试使用 Ninja Framework ( https://www.ninjaframework.org/documentation/testing_your_application/advanced.html ) 运行集成测试。该服务有一个 apiClient 实例,它使用改造与 3rd 方 API 交互。

class Service
@Inject
constructor(
        private val apiClient: ApiClient
)

我想模拟 apiClient.call 的响应。我尝试设置使用 Mock 注释的 apiClent 或使用 Service(apiClient) 初始化服务,但它与实际 API 交互并返回超时响应。

@RunWith(NinjaRunner::class)
class IntegrationTest {
    var apiClient: ApiClient = mock()

    @Inject
    var service: Service= mock()

    @Test
    fun `test something`() {
        whenever(apiClient.call()).thenReturn(
                RestResponse(status = RestResponse.Status.SUCCESS, message = "success")
        )

        val result = service.update()
    }
}
4

1 回答 1

0

集成测试意味着检查不同模块组合在一起时是否正常工作。* *单元测试意味着单独测试应用程序的各个模块,以确认代码是否正确。

因为您正在使用 apiClient 模拟服务测试您可能需要的是单元测试。

您不想模拟您实际测试的类,因此这里的一种方法是使用模拟对象初始化 Service,另一种方法是使用 @Mock 注释在运行时创建模拟。更多关于这里https://www.vogella.com/tutorials/Mockito/article.html

@RunWith(NinjaRunner::class)
class IntegrationTest {
    var apiClient: ApiClient = mock()

    var service: Service = Service(apiClient)

    @Test
    fun `test something`() {
        whenever(apiClient.call()).thenReturn(
                RestResponse(status = RestResponse.Status.SUCCESS, message = "success")
        )

        val result = service.update()
    }
}
于 2020-08-26T11:54:05.443 回答