【问题标题】:Mocking a class in integration tests with Java Ninja framework使用 Java Ninja 框架在集成测试中模拟一个类
【发布时间】:2020-12-15 04:02:31
【问题描述】:

我正在尝试使用 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()
    }
}

【问题讨论】:

    标签: java kotlin mockito ninjaframework


    【解决方案1】:

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

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

    您不想模拟您实际测试的课程 所以这里的一种方法是使用模拟对象初始化服务,另一种方法是使用 @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()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-17
      • 2010-10-21
      • 2010-10-30
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 2013-09-25
      相关资源
      最近更新 更多