单元测试来自 Groovy 测试用例的 Java 类中的静态方法 [英] Unit Testing a static method in a Java Class from Groovy Test case

查看:22
本文介绍了单元测试来自 Groovy 测试用例的 Java 类中的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a test case in groovy for a class that is written in java. The Java class(name:Helper) has a static method in it where a HttpClient object is obtained and executeMethod is called on it. To Unittest this class,I am trying to mock this httpClient.executeMethod() in groovy test case, but not able to mock it right.

下面是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 测试用例中模拟这个对象?

Any Ideas on how to unit test this static method from groovy. Since httpClient object is object inside the class method, how do i mock this object in groovy test case?

这是我到目前为止的测试用例.我试图模拟为空,但没有发生......

This is the test case that I have so far.I am trying to mock to null, but not happening...

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 等)声明闭包签名

You need to declare the closure signature with the correct Type i.e. String, Map, etc.

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

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

}

这篇关于单元测试来自 Groovy 测试用例的 Java 类中的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆