You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Mockito模拟javax.xml.ws.Service父类进行单元测试?

问题:测试继承自javax.xml.ws.Service的子类时绕过WSDL依赖

我有一个继承自javax.xml.ws.Service的Java类,正尝试用TestNG和Mockito为其编写单元测试。当前开发环境中,Service类所需的WSDL URL无法访问,导致无法创建Service实例,进而无法测试ServiceChild类的功能。我希望不依赖实际WSDL URL,通过模拟Service类并模拟其行为来测试ServiceChild类的功能。

待测试的ServiceChild类代码

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.ws.WebServiceException;

public class ServiceChild extends Service {
    private final static URL DEFAULT_URL;
    private final static QName DEFAULT_QNAME = new QName("http://example/qname", "ExampleName");

    static {
        URL wsdl = null;
        try {
            wsdl = new URL("https://wsdl/location");
        } catch (MalformedURLException e) {
            throw new WebServiceException(e);
        }
        DEFAULT_URL = wsdl;
    }

    public ServiceChild() {
        super(DEFAULT_URL, DEFAULT_QNAME);
    }
    public ServiceChild(URL wsdl, QName name) {
        super(wsdl, name);
    }
}

(注:修复了原代码中的语法错误:单引号改为双引号、构造方法末尾补分号、异常抛出语句修正)

当前遇到的问题

在单元测试中调用无参构造方法ServiceChild serviceChild = new ServiceChild();时,会出现如下错误:

java.net.ConnectException: Connection timed out: connect

已实现的解决方法

通过引入mockito-inline依赖,使用静态模拟的方式解决了该问题,测试方法示例如下:

import org.mockito.MockedStatic;
import org.mockito.Mockito;
import javax.xml.ws.spi.Provider;
import org.testng.Assert;
import org.testng.annotations.Test;

public class ServiceChildTest {
    @Test
    public void testConstructor() {
        try (MockedStatic<Provider> mockedStatic = Mockito.mockStatic(Provider.class)) {
            mockedStatic.when(Provider::provider).thenReturn(Mockito.mock(Provider.class));
            ServiceChild serviceChild = new ServiceChild();
            Assert.assertNotNull(serviceChild);
        }
    }
}

(注:修复了原测试代码的语法错误,补充了必要的导入语句和try-with-resources语法以正确管理静态模拟)

内容的提问来源于stack exchange,提问作者TechGoose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 22:25:55