2012-08-31 89 views
1

我想在用java编写的类的groovy中编写测试用例。 Java类(名称:Helper)有一个静态方法,在该方法中获得HttpClient对象并调用executeMethod。为了Unittest这个类,我试图在groovy测试用例中嘲笑这个httpClient.executeMethod(),但是无法正确地模拟它。单元测试Groovy中的Java类中的静态方法测试用例

下面是一个Java类

public class Helper{ 

    public static message(final String serviceUrl){ 

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

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

    } 
} 

任何想法单元如何测试从常规此静态方法。由于httpClient对象是类方法内的对象,我如何在groovy测试用例中嘲笑这个对象?

这是测试的情况下,我有这么far.I我试图嘲弄为空,但不会发生......

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) 

    } 
} 

回答

0

您可以使用

HttpClient.metaClass.executeMethod = {Type name -> doSomething} 

您需要声明结束签名与正确Type即字符串,地图等

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

    // mocking to return null 
    HttpClient.metaClass.executeMethod = {HttpMethod str -> null} 
    def responseXml = helper.message(serviceUrl) 

} 
+0

感谢您的答复。但是,不明白封闭在做什么。我知道executeMethod被添加到HttlpClient的元类中。你能否解释一下{类型名称 - > doSomething}。此外,更新了我迄今为止编写的测试用例 – Npa

+0

闭包正在替代(模拟)来自'executeMethod'的原始代码当您执行测试时,将执行闭包,而不是原始代码。类型名称 - > doSomething只是虚拟示例代码。您需要编写正确的参数类型来执行该闭包。 –

+1

hmmm ....上面的代码不会将其嘲讽为null.httpClient.executeMethod(方法)返回200但不为空。不知是否 HttpClient httpclient = new HttpClient(); 与不能嘲笑它有任何关系。 – Npa