【问题标题】:Unit Testing a static method in a Java Class from Groovy Test case从 Groovy 测试用例对 Java 类中的静态方法进行单元测试
【发布时间】:2012-08-31 15:47:10
【问题描述】:

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

    }
}

关于如何从 groovy 对这个静态方法进行单元测试的任何想法。由于 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)

    }   
}

【问题讨论】:

    标签: java grails groovy junit mocking


    【解决方案1】:

    你可以使用

    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)
    
    }
    

    【讨论】:

    • 感谢您的回复。但是,不明白闭包在做什么。我知道 executeMethod 被添加到 HttlpClient 的元类中。您能否解释一下{Type name -> doSomething}。另外,更新了我目前写的测试用例
    • 闭包正在替换(模拟)来自executeMethod 的原始代码当您执行测试时,将执行闭包而不是原始代码。类型名称 -> doSomething 只是虚拟示例代码。您需要编写正确的参数类型才能执行该闭包。
    • hmmm....上面的代码没有将其模拟为 null。httpClient.executeMethod(method) 返回 200 但不为 null。我想知道 HttpClient httpclient = new HttpClient();与无法模拟它有关。
    猜你喜欢
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2016-06-20
    • 2020-09-06
    • 2019-05-11
    相关资源
    最近更新 更多