How to pass context from Script to another Class groovy

若如初见. 提交于 2019-12-13 01:44:07

问题


Below is my Groovy Script which instantiates my classes. It is a part of a much larger Groovy Script, consisting of many classes, which sits as a Test Case within a Test Suite in SoapUI :

public class Run extends Script {
public static void main (String[] args){
    Run mainRun = new Run()
}
public run(){
    def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context ); // Would not error
    Model myModel = new Model()
    View myView = new View()
    Controller myController = new Controller()
    myModel.addObserver (myView)
    myController.addModel(myModel)
    myController.addView(myView)
    myController.initModel("Init Message")
    myView.addController(myController)
}}

Within the above 'Run' class, (if I wanted to), I am able to refer to the 'context' - in order to define GroovyUtils. How do I pass the 'context' to another class, the Model, in order to use GroovyUtils in the Model? I.e:

class Model extends java.util.Observable {
public String doSomething(){
    def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );// Error occurs here
    return "Stuff that needs groovyUtils"
}}

The above code would cause an error when trying to refer to the context, despite it being within the same Groovy Test Step as the 'Run' class. Any help would be greatly appreciated.


回答1:


I'm not sure if I understand correctly all the pieces of your model, however as @tim_yates suggest in his comment why you don't simply pass the groovyUtils to your Model class. You can modify your Model class adding a groovyUtils variable:

class Model extends java.util.Observable {

    com.eviware.soapui.support.GroovyUtils groovyUtils

    public String doSomething(){
            println this.groovyUtils// here you've groovy utils
            return "Stuff that needs groovyUtils"
    }   
}

And then in the run() method pass the groovyUtils to the Model class using the groovy default map constructor:

public class Run extends Script {
public static void main (String[] args){
    Run mainRun = new Run()
}
public run(){
    def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context ); // Would not error
    Model myModel = new Model('groovyUtils':groovyUtils) // pass the groovyUtils to your Model
    assert "Stuff that needs groovyUtils" == myModel.doSomething() // only to check the groovyUtils is passed to your model class
    assert myModel.groovyUtils == groovyUtils
    ...
}}

Hope it helps,



来源:https://stackoverflow.com/questions/33437415/how-to-pass-context-from-script-to-another-class-groovy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!