Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
Mockk spied class with anonymous class field references original (non-spied) object

When using Mockk to spy a Kotlin or Java class, if the class has a field that is an anonymous class (like View.OnClickListener), when the field functions reference the parent class, it is not reflected on the spied object.

Example Class with anonymous class field:

class MyClass {
    var myString: String? = null
        set(value) {
            println("myString set to ${value?.hashCode()} for ${this@MyClass.hashCode()}")
            field = value
        }

    val myStringWrapper: StringWrapper = object : StringWrapper {
        val timestamp = System.currentTimeMillis()
        override fun setString(string: String) {
            println("myStringWrapper ${this.hashCode()} for ${this@MyClass.hashCode()}")
            myString = string
        }
    }
    
    fun setString(string: String) {
        myString = string
    }

    interface StringWrapper {
        fun setString(string: String)
    }
}

Example Unit Test

    @Test
    fun testSpyAndRealMyClassStringWrapper2() {
        val realMyClass = MyClass()
        println("realMyClass hash is ${realMyClass.hashCode()}")
        realMyClass.myStringWrapper.setString("Hello World")
        println("realMyClass myString value ${realMyClass.myString}")
        println()
        
        val spyMyClass = spyk(MyClass())
        println("spyMyClass hash is ${spyMyClass.hashCode()}")
        spyMyClass.myStringWrapper.setString("Hello World")
        println("spyMyClass myString value ${spyMyClass.myString}")
    }

Unit Test Results

realMyClass hash is 896791337
myStringWrapper 1919243391 for 896791337
myString set to -862545276 for 896791337
realMyClass myString value Hello World

spyMyClass hash is 1153593788
myStringWrapper 971441251 for 1519093944
myString set to -862545276 for 1519093944
spyMyClass myString value null

The Spied class clearly shows a different hashcode when accessed via the anonymous class than the spied class has, and the myString does not end up set (as it returns null). If the spied MyClass is extracted as it's own variable, that item's myString field will return the "Hello World" expected from the spy.

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!