单位在Groovy测试用例在Java类测试静态方法(Unit Testing a static me

2019-06-27 15:52发布

我试图写在常规的测试案例是用Java编写的类。 Java类(名称:助手)具有其中获得一个HttpClient的对象和executeMethod上调用它在它的静态方法。 为了单元测试这个类,我想这嘲笑httpClient.executeMethod()在常规测试情况,但不能嘲笑它的权利。

下面是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我试图嘲弄为null,但没有发生...

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)

    }   
}

Answer 1:

您可以使用

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)

}


文章来源: Unit Testing a static method in a Java Class from Groovy Test case