gpt4 book ai didi

java - 从 Groovy 测试用例对 Java 类中的静态方法进行单元测试

转载 作者:行者123 更新时间:2023-12-01 05:09:31 25 4
gpt4 key购买 nike

我正在尝试用 groovy 为用 java 编写的类编写一个测试用例。 Java 类(名称:Helper)中有一个静态方法,其中获取 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);

}
}

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

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

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}

您需要使用正确的类型声明闭包签名,即字符串、映射等。

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

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

}

关于java - 从 Groovy 测试用例对 Java 类中的静态方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12218699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com