How to share variables across multiple cucumber step definition files with groovy

*爱你&永不变心* 提交于 2019-12-10 21:53:50

问题


I am using cucumber jvm to write tests with groovy. Up until now, I have had all of my step definitions in one file, and everything has worked perfectly. I am now looking to move the step definitions to seperate files, as I have a lot of them. The problem I am having is with instance variables. I tried to make my step definitions as generic as possible, so any annotated with @when returned an object called response, and any definitions annotated with @then asserted something on the response. My question is, is there are a way that I can have these stored in separate files? I have read a little about the 'World' but I am not sure if that is what I am looking for, and despite looking at the example project on github (https://github.com/cucumber/cucumber-jvm/blob/master/groovy/src/test/groovy/cucumber/runtime/groovy/compiled_stepdefs.groovy), I cannot get this to work.

An example of what I am trying to achieve would be something like this:

 Scenario:
 When I say hello
 Then Hello should be printed

As my scenario. I then want to have two classes that share variables like so:

 class sayHello{

   def response     

   @When('^I say hello$')
   def iSayHello() {
     response = "hello"
   }
 }

 class printHello{

   @Then('^Hello should be printed$')
   def iPrintHello() {
     assert response == "hello"
   }
 }

I know that i could use spring to inject the variables into the classes, but I was wondering if there was another way, and if I was on the right tracks with the 'World' object. Thanks in advance


回答1:


I have found a solution to this using groovy's mixin functionality. mixin allows a class to inherit the methods of another class, and also use the classes variables at runtime.

Using the above example, my solution looks like this:

@Mixin(printHello)
class sayHello {

   @When('^I say hello$')
   def iSayHello() {
     response = "hello"
   }
}

class printHello {

   static def response

   @Then('^Hello should be printed$')
   def iPrintHello() {
      assert response == "hello"
   }
}

This allows me to generically set the response object from any class, and then make an assertion on it in the common steps file.



来源:https://stackoverflow.com/questions/20099934/how-to-share-variables-across-multiple-cucumber-step-definition-files-with-groov

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