单元从Groovy测试用例测试Java类中的静态方法

我试图在groovy中编写一个用java编写的类的测试用例。 Java类(名称:Helper)中有一个静态方法,其中获取HttpClient对象并在其上调用executeMethod。 为了对这个类进行Unittest,我试图在groovy测试用例中模拟这个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); } } 

关于如何从groovyunit testing这个静态方法的任何想法。 由于httpClient对象是类方法中的对象,我如何在groovy测试用例中模拟这个对象?

这是我到目前为止的测试用例。我试图模拟为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) } } 

您可以使用

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

您需要使用正确的Type声明闭包签名,即String,Map等。

 void testSendMessage(){ def serviceUrl = properties.getProperty("ITEM").toString() // mocking to return null HttpClient.metaClass.executeMethod = {HttpMethod str -> null} def responseXml = helper.message(serviceUrl) }