gpt4 book ai didi

java - 模拟最终类及其抛出异常的方法

转载 作者:行者123 更新时间:2023-11-30 08:41:57 25 4
gpt4 key购买 nike

我有一个最终类,它尝试使用 openConnection() 连接到提供的 URL。我 mock 它让它返回一个 UnknownHostException 因为我知道提供的 URL 是未知的并且还减少了单元测试的时间(> 0.01 秒对于这个测试来说太长了)。

要测试的类:

public final class Server {
private Server() {}

public static void getServerStuff(final URL url) throws IOException {
try {
final URLConn urlConn;
// immediately throw exception without trying to make a connection
urlConn = url.openConnection();
}
catch (Exception e) {
// not relevant
}
}
}

单元测试

public class ServerTest {

public class UrlWrapper {

Url url;

public UrlWrapper(String spec) throws MalformedURLException {
url = new URL(spec);
}

public URLConnection openConnection() throws IOException {
return url.openConnection();
}
}

public void testUnknownHostExceptionIsThrown() throws IOException {

UrlWrapper mockUrl = mock(UrlWrapper.class);
URLConnection mockUrlConn = mock(URLConnection.class);

when(mockUrl.openConnection()).thenThrow(UnknownHostException.class);

final String server = "blabla";
final URL url = new URL("http://" + server);
mockUrl.url = url;

try {
Server.getServerStuff(mockUrl.url);
}
catch (IOException e) {
// do stuff with Assert
}
}
}

我需要使用 mockito 而不是可以模拟 final类的 powermockito。我的主要问题是我不知道如何告诉单元测试使用我模拟的 openConnection()。它仍应测试我的 getServerStuff() 方法,但在没有实际尝试连接的情况下抛出异常。

我需要更改什么才能使其正常工作?

编辑: 我不认为它与所引用的问题重复,因为我知道如何模拟最终类(例如使用包装器)。我的问题是下一步,这意味着如何使用我的模拟方法。我的单元测试将进入待测试方法并使用标准库中的 openConnection(),但我希望它使用我的模拟方法来减少完成此单元测试所需的时间。

最佳答案

当您将包装的 URL 对象传递给 Server 时,UrlWrapper 的用途是什么?

我假设您可以编辑 Server

就我个人而言,我会创建一个新接口(interface),该接口(interface)将传递给您的 Server#getServerStuff(..) 方法。然后,您可以模拟界面以提供您想要的模拟行为。

public interface ServerRemote {
public InputStream getInput() throws IOException
}

public class URLServerRemote implements ServerRemote {

private URL url;

public URLServerRemote(URL url) {
this.url = url;
}

public InputStream getInputStream() throws IOException {
return url.openConnection().getInputStream();
}
}

public final class Server {
private Server() {}

public static void getServerStuff(final ServerRemote remote) throws IOException {
try {
final InputStream input;
// immediately throw exception without trying to make a connection
input = remote.getInputStream();
}
catch (Exception e) {
// not relevant
}
}
}

...

public void testUnknownHostExceptionIsThrown() throws IOException {

ServerRemote mockServerRemote = mock(ServerRemote.class);
when(mockServerRemote.getInputStream()).thenThrow(UnknownHostException.class);

try {
Server.getServerStuff(mockServerRemote);
}
catch (IOException e) {
// do stuff with Assert
}
}

...

如果您不能更改您的 Server 类,那么除非您使用 PowerMock,否则您将被卡住。

关于java - 模拟最终类及其抛出异常的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34769363/

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