title: How to initialise/wire beans in Grails Spock unit tests?
body: <p>I'm wanting to test a Grails controller that contains a bean (I'll move it to a Service when I get it working, but I just want to keep it simple now).</p>
  
  <pre><code>//resources.groovy
  beans {
      myBean(com.me.MyBean) 
  }
  
  
  // MyBean.java
  // this needs to be in java as it is playing with spring-data-neo4j
  package com.me;
  public class MyBean {
      String show() {
          return "Hello";
      }
  }
  
  // TestController.groovy
  package com.me
  
  import com.me.MyBean
  
  class TestController {
  
      def myBean
  
      def index() {
          render myBean.show()
      }
  }
  
  
  // TestControllerSpec.groovy
  package com.me
  
  import grails.test.mixin.TestFor
  import spock.lang.Specification
  
  import com.me.*
  
  @TestFor(TestController)
  class TestControllerSpec extends Specification {
  
      def myBean
  
      def setup() {
          defineBeans {
              myBean(com.me.MyBean) {bean-&gt;
                  bean.autowire = true
              }
          }
      }
  
      def cleanup() {
      }
  
      def "show() returns Hello"() {
          when:
          def rc = controller.myBean.show()
          def rc2 = myBean.show()
  
          then:
          rc == "Hello"
          rc2 == "Hello"
      }
  }
  </code></pre>
  
  <p>Within TestControllerSpec, myBean is null.  controller.myBean is also null.  I think this is because Spring is not picking the bean up and wiring it in.  I gather that in unit tests not all spring beans are available, but what do I need to do to get controller.myBean to be instantiated and wired up correctly?</p>