从Groovy测试用例中模拟Java类

时间:2012-08-28 17:45:20

标签: java grails groovy junit mocking

我正在尝试用groovy编写一个用java编写的类的测试用例。 Java类(名称:Helper)中有一个方法,其中获取HttpClient对象并在其上调用executeMethod。我试图在groovy测试用例中模拟这个httpClient.executeMethod(),但是无法正确模拟它。

以下是Java类 //这个助手类是一个java类

public class Helper{

public static message(final String serviceUrl){   
----------some code--------

HttpClient httpclient = new HttpClient();
HttpMethod httpmethod = new HttpMethod();

// the below is the line that iam trying to mock
String code = httpClient.executeMethod(method);

}
}

到目前为止我在groovy中编写的测试用例是:

    void testSendMessage(){
        def serviceUrl = properties.getProperty("ITEM").toString()

    // mocking to return null   
def mockJobServiceFactory = new MockFor(HttpClient)
    mockJobServiceFactory.demand.executeMethod{ HttpMethod str ->
                return null
            }

    mockJobServiceFactory.use {         
             def responseXml = helper.message(serviceUrl)

            }   
        }

关于为什么它没有正确嘲笑的任何想法。 提前谢谢

2 个答案:

答案 0 :(得分:0)

嘛! 除非将它们声明为属性,否则很难测试静态方法,甚至更难测试局部变量。我关于静态类的结论有时是关于设计的,因为你可以把这个代码块放在其他地方并重用。无论如何,这是我的测试方法,没有任何东西,存根,模拟和MOP这种情况:

这是一个像你的类一样的Java类:

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class Helper{

  public static String message(final String serviceUrl) throws ParseException{
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy");
    Date d = formatter.parse(serviceUrl);
    String code = d.toString();
    return code;
  }
}

这是我的GroovyTestCase:

import groovy.mock.interceptor.MockFor
import groovy.mock.interceptor.StubFor
import java.text.SimpleDateFormat

class TestHelper extends GroovyTestCase{

  void testSendMessageNoMock(){
    def h = new Helper().message("01-01-12")
    assertNotNull h
    println h
  }

  void testSendMessageWithStub(){
    def mock = new StubFor(SimpleDateFormat)
    mock.demand.parse(1..1) { String s -> 
      (new Date() + 1) 
    }
    mock.use {
      def h = new Helper().message("01-01-12")
      assertNotNull h
    }
  }

  void testSendMessageWithMock(){
    def mock = new MockFor(SimpleDateFormat)
    mock.demand.parse(1..1) { String s -> 
      (new Date() + 1) 
    }
    shouldFail(){
      mock.use {
        def h = new Helper().message("01-01-12")
        println h
      }  
    }
  }

  void testSendMessageWithMOP(){
    SimpleDateFormat.metaClass.parse = { String s -> 
      println "MOP"
      new Date() + 1 
    }
    def formatter = new SimpleDateFormat()
    println formatter.parse("hello world!")
    println " Exe: " +  new Helper().message("01-01-12")
  }
}

您的问题的答案可能是:因为是方法中的局部变量,而不是要测试的协作者。

此致

答案 1 :(得分:0)

它不起作用,因为编译的Java类在构造 HttpClient 实例时不会通过Groovy的元对象协议(MOP),因此模拟的对象不会被实例化。

由于 HttpClient 实例是线程安全的,我会考虑将它作为依赖项注入到类中,这样测试可以简单地注入模拟。

相关问题