JUnit测试URLConnection,使用EasyMock?

发布于 2024-10-31 01:07:10 字数 1219 浏览 1 评论 0原文

嘿,最近一天左右一直在尝试解决这个问题,但遇到了困难。尝试对这段代码进行单元测试。但不确定是否需要使用EasyMock?网上的例子似乎很少,但似乎使用的是较旧的技术。

public boolean verifyConnection(final String url) {
    boolean result;

    final int timeout = getConnectionTimeout();
    if (timeout < 0) {
        log.info("No need to verify connection to client. Supplied timeout = {}", timeout);
        result = true;
    } else {
        try {
            log.debug("URL: {} Timeout: {} ", url, timeout);

            final URL targetUrl = new URL(url);
            final HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();

            connection.setConnectTimeout(timeout);
            connection.connect();
            result = true;
        } catch (ConnectException e) {
            log.warn("Could not connect to client supplied url: " + url, e);
            result = false;
        } catch (MalformedURLException e) {
            log.error("Malformed client supplied url: " + url, e);
            result = false;
        } catch (IOException e) {
            log.warn("Could not connect to client supplied url: " + url, e);
            result = false;
        }
    }
    return result;
}

它只是在 url 中检查其有效性并返回 T 或 F。

Hey, have been trying to work this out for last day or so but hitting brick wall. Trying to unit test this bit of code. But not sure if need to use EasyMock or not?? Seem few examples online but seem to be using older techniques.

public boolean verifyConnection(final String url) {
    boolean result;

    final int timeout = getConnectionTimeout();
    if (timeout < 0) {
        log.info("No need to verify connection to client. Supplied timeout = {}", timeout);
        result = true;
    } else {
        try {
            log.debug("URL: {} Timeout: {} ", url, timeout);

            final URL targetUrl = new URL(url);
            final HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();

            connection.setConnectTimeout(timeout);
            connection.connect();
            result = true;
        } catch (ConnectException e) {
            log.warn("Could not connect to client supplied url: " + url, e);
            result = false;
        } catch (MalformedURLException e) {
            log.error("Malformed client supplied url: " + url, e);
            result = false;
        } catch (IOException e) {
            log.warn("Could not connect to client supplied url: " + url, e);
            result = false;
        }
    }
    return result;
}

It just take's in a url checks its valid and returns T or F.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

っ左 2024-11-07 01:07:11

我一直认为可以尽可能避免 Mocking,因为它会导致难以维护 JUnit 测试并达不到整个目的。

我的建议是从 JUnit 本身在本地计算机上创建一个临时服务器。
在 JUnit 的开头,您可以使用 Java 套接字创建一个服务器(所需的代码不超过 10-15 行),然后在代码中传递本地服务器的 URL。通过这种方式,您可以减少模拟并确保最大的代码覆盖率。

像这样的东西 -

public class SimpleServer extends Thread {

public void run() {
    try {
        serverSocket = new ServerSocket(port);

          while (true) {
            Socket s = serverSocket.accept(); 
          }
    } 
    catch (IOException e) {
            e.printStackTrace();
    }
    finally {
        serverSocket = null;
    }
}
}

I have always observed that Mocking Can be avoided as much as possible because it can lead to difficult to maintain JUnit tests and defeat the whole purpose.

My suggestion would be to create a temporary server on your local machine from a JUnit itself.
At the beginning of JUnit you can create a server(not more than 10-15 lines of coding required) using Java sockets and then in your code pass the URL for the local server. This way you are reducing mocking and ensuring maximum code coverage.

Something like this -

public class SimpleServer extends Thread {

public void run() {
    try {
        serverSocket = new ServerSocket(port);

          while (true) {
            Socket s = serverSocket.accept(); 
          }
    } 
    catch (IOException e) {
            e.printStackTrace();
    }
    finally {
        serverSocket = null;
    }
}
}
摘星┃星的人 2024-11-07 01:07:11

如果您想模拟此方法,我建议您传入 URL 而不是字符串。不要让你的方法创建它需要的 URL;让客户端为您创建 URL 并将其传递进去。这样您的测试就可以在需要时替换模拟。

这几乎是一个依赖注入的想法——你的方法应该被赋予它的依赖项,而不是自己创建它们。对“新”的呼唤是致命的赠品。

这不是一个巨大的变化。您可以重载该方法并拥有两个签名:一个接受 URL 字符串,另一个接受 URL 本身。让第一个方法创建 URL 并调用第二个方法。这样您就可以对其进行测试,并且仍然可以在 API 中使用带有 String 签名的方法,以方便使用。

If you want to mock this method, I'd recommend passing in the URL rather than the String. Don't have your method create the URL it needs; let the client create the URL for you and pass it in. That way your test can substitute a mock if it needs to.

It's almost a dependency injection idea - your method should be given its dependencies and not create them on its own. The call to "new" is the dead giveaway.

It's not a drastic change. You could overload the method and have two signatures: one that accepts a URL string and another that accepts the URL itself. Have the first method create the URL and call the second. That way you can test it and still have the method with the String signature in your API for convenience.

浪漫之都 2024-11-07 01:07:11

尝试设置 HttpURLConnection 的模拟实现。就像

public class MockHttpURLConnection extends HttpURLConnection {'

然后向类添加方法来重写

' protected HttpURLConnection createHttpURLConnection(URL url)
        throws IOException {
    return (HttpURLConnection) url.openConnection();
}

所以测试看起来像这样:

@Test
public void testGetContentOk() throws Exception
{
    String url = "http://localhost";

    MockHttpURLConnection mockConnection = new MockHttpURLConnection();

    TestableWebClient client = new TestableWebClient();
    client.setHttpURLConnection(mockConnection);

    boolean result = client.verify(url);

    assertEquals(true, result);
}

@Test
public void testDoesNotGetContentOk() throws Exception
{
    String url = "http://1.2.3.4";

    MockHttpURLConnection mockConnection = new MockHttpURLConnection();

    TestableWebClient client = new TestableWebClient();
    client.setHttpURLConnection(mockConnection);

    boolean result = client.verify(url);

    assertEquals(false, result);
}

/**
 * An inner, private class that extends WebClient and allows us
 * to override the createHttpURLConnection method.
 */
private class TestableWebClient extends WebClient1 {

    private HttpURLConnection connection;

    /**
     * Setter method for the HttpURLConnection.
     *
     * @param connection
     */
    public void setHttpURLConnection(HttpURLConnection connection)
    {
        this.connection = connection;
    }

    /**
     * A method that we overwrite to create the URL connection.
     */
    @Override
    public HttpURLConnection createHttpURLConnection(URL url) throws IOException
    {
        return this.connection;
    }
}

第一部分通过了,但对于虚假的虚拟测试来说是正确的,感谢迄今为止最好的网站的反馈已找到帮助。所以请告诉我是否在正确的轨道上思考

Trying to set up mock implementation of the HttpURLConnection. Like

public class MockHttpURLConnection extends HttpURLConnection {'

then added method to class to override

' protected HttpURLConnection createHttpURLConnection(URL url)
        throws IOException {
    return (HttpURLConnection) url.openConnection();
}

So test looking something like this:

@Test
public void testGetContentOk() throws Exception
{
    String url = "http://localhost";

    MockHttpURLConnection mockConnection = new MockHttpURLConnection();

    TestableWebClient client = new TestableWebClient();
    client.setHttpURLConnection(mockConnection);

    boolean result = client.verify(url);

    assertEquals(true, result);
}

@Test
public void testDoesNotGetContentOk() throws Exception
{
    String url = "http://1.2.3.4";

    MockHttpURLConnection mockConnection = new MockHttpURLConnection();

    TestableWebClient client = new TestableWebClient();
    client.setHttpURLConnection(mockConnection);

    boolean result = client.verify(url);

    assertEquals(false, result);
}

/**
 * An inner, private class that extends WebClient and allows us
 * to override the createHttpURLConnection method.
 */
private class TestableWebClient extends WebClient1 {

    private HttpURLConnection connection;

    /**
     * Setter method for the HttpURLConnection.
     *
     * @param connection
     */
    public void setHttpURLConnection(HttpURLConnection connection)
    {
        this.connection = connection;
    }

    /**
     * A method that we overwrite to create the URL connection.
     */
    @Override
    public HttpURLConnection createHttpURLConnection(URL url) throws IOException
    {
        return this.connection;
    }
}

First part passed but is getting true for false dummy test, thanks for feedback back so far best site I have found for help. So let me know if think on right track

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文