title: Using Groovy MetaClass to overwrite Methods
body: <p>I have a POJO that uses a service to do something:</p>
  
  <pre><code>public class PlainOldJavaObject {
  
      private IService service;
  
      public String publicMethod(String x) {
          return doCallService(x);
      }
  
      public String doCallService(String x) {
          if(service == null) {
              throw new RuntimeException("Service must not be null");
          }
          return service.callX(x);
      }
  
      public interface IService {
          String callX(Object o);
      }
  }
  </code></pre>
  
  <p>And I have a Groovy test case:</p>
  
  <pre><code>class GTest extends GroovyTestCase {
  
      def testInjectedMockIFace() {
          def pojo = new PlainOldJavaObject( service: { callX: "very groovy" } as IService )
          assert "very groovy" == pojo.publicMethod("arg")
      }
  
      def testMetaClass() {
          def pojo = new PlainOldJavaObject()
          pojo.metaClass.doCallService = { String s -&gt;
              "no service"
          }
          assert "no service" == pojo.publicMethod("arg")
      }
  }
  </code></pre>
  
  <p>The first test method, <code>testInjectedMockIFace</code> works as expected: The POJO is created with a dynamic implementation of <code>IService</code>. When <code>callX</code> is invoked, it simply returns "very groovy". This way, the service is mocked out. </p>
  
  <p>However I don't understand why the second method, <code>testMetaClass</code> does not work as expected but instead throws a NullPointerException when trying to invoke <code>callX</code> on the service object. I thought I had overwritten the <code>doCallService</code> method with this line:</p>
  
  <pre><code>pojo.metaClass.doCallService = { String s -&gt;
  </code></pre>
  
  <p>What am I doing wrong?</p>
  
  <p>Thanks!</p>