【问题标题】:Koin Unit testing how to verify whether a class method was called when injected by "by inject()"Koin单元测试如何验证通过“注入()”注入时是否调用了类方法
【发布时间】:2020-07-29 13:25:19
【问题描述】:

我有一门课程,我已经为其编写了单元测试。该类通过构造函数注入 2 个其他类。但是由于循环依赖问题,我不得不通过注入()注入其他依赖项之一。

我的班级如下所示:

class AuthUseCase(
    private val accessTokenUseCase: AccessTokenUseCase,
    private val refreshTokenRepo: RefreshTokenRepo
) : KoinComponent {

    val notificationService: NotificationService by inject()



    fun getSyncedAccessToken(loginResult: LoginResult): Token? {
        return when (loginResult) {
            is LoginResult.Success -> {
                accessTokenUseCase.storeRefreshToken(loginResult.accessToken)
                notificationService.init()
                loginResult.accessToken.accessToken
            }
            is LoginResult.Failure -> {
                null
            }
        }
    }
}

我想测试我的测试中是否触发了 notificationService.init。 通常它会很简单

verify(notificationService).init()

但是我无法理解如何模拟这个类。任何帮助将不胜感激。

【问题讨论】:

标签: android unit-testing koin


【解决方案1】:

感谢@Mariuz 并通过这篇文章: https://github.com/InsertKoinIO/koin/issues/197#issuecomment-429768448

诀窍是启动一个空的 Koin 容器。并在测试中加载模拟模块。

@Test
fun testGetValidAccessTokenIfInvalidAccessTokenIsPassed() {
    notificationService = mock()
    startKoin { }
    loadKoinModules(module {
        single {
            notificationService
        }
    })
   

    verify(notificationService).init()
}

【讨论】:

  • 很高兴为您提供帮助!酷!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多