【发布时间】:2020-12-18 22:30:54
【问题描述】:
我在使用 mockito 模拟带有伴随对象的类时遇到问题。看起来和这个很像
@Component
class Util {
companion object {
fun generateName(job: Job) {
return job.name + "_" + (System.currentTimeMillis()/100L).toString()
}
}
}
我正在尝试模拟这个类,所以我可以做这样的事情:
我在测试文件中模拟了该实用程序,例如
var util : Util.Companion = mock()
现在在我的测试中,我想做以下事情:
@Test
fun "test function"() { //(dont have the symbols, not using the work laptop, excuse the syntax error)
whenever(util.generateName(job)).thenReturn("mystring")
}
由于我们的作业名称包含时间戳,我需要它来工作,否则我的单元测试将无法工作。不用说,这无论何时都不起作用,并且我的函数在模拟时返回“正确”结果,而不是我希望在 return 子句中提供的结果,否则在插入期间我总是会得到空值,因为我无法模拟时间戳。请不要建议不同的模拟库等,已经有近 100 个使用 mockito 编写的测试,所以这不是一个选择。
【问题讨论】:
标签: unit-testing kotlin mockito companion-object