unit testing - Set property to a mocked object using mockito - Stack Overflow

admin2025-05-01  0

I am trying to set a property for my mocked object, in my testing code, the mocked object is followed by an apply to set a property value.

I found out that despite this block ran, the property value is not set.

/* class under test" */
class MyClass {
  val obj = NativeClass().apply {
    property = {
       callbacks()
    }
  }
}

/* My testing*/
private lateinit var myClass
@Before
fun setup() {
  mockConstruction(NativeClass.class.java)
  myClass = MyClass()
}

@Test
fun `test` {
 assertNotNull(myClass.obj) //pass
 assertNotNull(myClass.obj.property) //fail
}

My goal is to test that callbacks are triggered, but does not seems like the property can be set. I can't directly initiate and use NativeClass, because there's external function that requires so in the initialization block. What's the best way for me to achieve my goal for testing ?

转载请注明原文地址:http://anycun.com/QandA/1746102922a91705.html