mardi 28 avril 2015

How to use mocking in this case?

Here is my problem:

This is the method for which i am trying to write test case.

This method trying to create instance of "HttpClient" but this server is not available on my side.

So i am trying to achieve this by using mocking, But i am not successful in that.

So could anyone tell me that how to do that?

Here is the method:

  public boolean callGet(final boolean keepResult) {
            boolean ok = false;
            if (url != null) {
                try {
                    log.appendLine("Url:");
                    log.append(url);
                    final HttpClient client = new HttpClient();
                    setAuthentication(client);
                    final GetMethod method = new GetMethod(url);
                    if (Utils.isFilled(userAgent)) {
                        method.setRequestHeader("User-Agent", userAgent);

                    }
                    status = client.executeMethod(method);
                    ok = (status == HttpStatus.SC_OK);
                    log.appendLine("Status http call:");
                    log.append(status);
                    if (ok) {
                        if (keepResult) {
                            if (maxSizeResult > 0) {
                                result = method
                                        .getResponseBodyAsString(maxSizeResult);

                            } else {
                                result = method.getResponseBodyAsString();

                            }
                        }
                    }
                } catch (final Exception e) {
                }
            }
            return ok;

This is my unit test method:

   @Before
        public void start() {
            urlcaller = new UrlCaller();
            UrlCaller mock1 = Mockito.mock(UrlCaller.class);
            Mockito.when(mock1.callGet(true)).thenReturn(true);

        }

        @Test
        public void testSetUserAgent() throws HttpException, IOException {

        boolean t1 = urlcaller.callGet(true);

        System.out.println(t1);

    }

}

This is the error i am getting :

Problem:
    UrlCaller.java
    javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:946)
        ...
        at de.bcode.utilsWithLog.UrlCaller.callGet(UrlCaller.java:115)
        at de.bcode.utilsWithLog.TestUrlCaller.testSetUserAgent(TestUrlCaller.java:52)
    Caused by:
        java.io.EOFException: SSL peer shut down incorrectly
            at sun.security.ssl.InputRecord.read(InputRecord.java:482)
            ...
            at de.bcode.utilsWithLog.UrlCaller.callGet(UrlCaller.java:115)
            at de.bcode.utilsWithLog.TestUrlCaller.testSetUserAgent(TestUrlCaller.java:52)
false

Thank you for reading all the question :-) Hope it is clear enough.

Aucun commentaire:

Enregistrer un commentaire