使用Java Ninja框架模拟集成测试中的类

问题描述

我正在尝试使用Ninja Framework(https://www.ninjaframework.org/documentation/testing_your_application/advanced.html)进行集成测试。 该服务具有一个apiclient实例,该实例可使用改型与第三方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()
    }
}

解决方法

集成测试是指将不同的模块作为一个整体组合在一起时是否可以正常工作。* * 单元测试是指单独测试应用程序的各个模块,以确认代码是否正确运行。

因为您正在使用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()
    }
}