我正在尝试使用Koin编写单元测试,其中对象没有通过构造函数传递。
class RandomClass {
fun execute() {
val someDependency: SomeClass by Inject(SomeClass::class.java)
someDependency.doSomething()
}
}
我这样设置了单元测试
class UnitTestFile: KoinTest {
@Before
override fun setup() {
startKoin {
modules(commonModule) //Module where it lives
}
}
@After
fun tearDown() {
stopKoin()
}
//This test does not work. It says doSomething was not called
@Test
fun `RandomObject's someDependency doSomething is called on execute`() {
val someDependency = declareMock<SomeClass>()
val randomClass = RandomClass()
randomClass.execute()
verify(someDependency).doSomething() //Failure
}
//If on the other hand, execute took a someClass, it does work
@Test
fun `RandomObject's someDependency doSomething is called on execute`() {
val someDependency = declareMock<SomeClass>()
val randomClass = RandomClass()
randomClass.execute(someDependency)
verify(someDependency).doSomething() //Success
}
真正奇怪的是,我知道我的模拟程序在不将其传递给构造函数时仍在工作,因为我可以做到这一点,因此测试将抛出NullPointerException
@Test
fun `RandomObject someDependency doSomething is called`() {
val someDependency = declareMock<SomeClass>() {
given(doSomething()).willThrow(NullPointerException())
}
val randomClass = RandomClass()
randomClass.execute() //Throws Null Pointer Exception
verify(someDependency).doSomething()
}
那么,当我的模拟没有注入构造函数时为什么还能工作,但我无法对其进行验证?