Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

257
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda