Spock Web Console

subscribe to the feed Subscribe
Reflection on Instance (via #spockwebconsole)
tweet this script Tweet

Reflection on Instance

Published 1 year ago by Victor Cabell with tags refection
Actions  ➤ Edit In Console Back To Console Show/Hide Line Numbers View Recent Scripts
import spock.lang.*

// Hit 'Run Script' below
class MyFirstSpec extends Specification {
  def "Add method on runtime in a single instance"() {    
    given:
    def test = "test"
    def gstr = "hello $test"     // this is a GString, which implements GroovyObject
 
    def emc = new ExpandoMetaClass( gstr.class, false )
    emc.test = { return"test" }
    emc.initialize()
 
    gstr.metaClass = emc

    when:
    def result = gstr.test()
    
    then:
    result == 'test'
    
  }
    
  def "Trying to invoke method definied in the privous testcase"() {
    when:
    "Test".test()
    then:
    thrown(MissingMethodException)
  }

}