1

I have the below method in my class , but I am unable to mock it , because I am writing j-unit test cases(using powerMockito) , so I am not able to communicate with the server . Can any body point out a solution to do at this stage . because when the Socket s = new Socket(ip, port); gets called my exception block will caught it with the message unable to connect with the port

private byte[] testMethod(String ip, int port, byte content[])
    {

        Socket s;
        BufferedReader in;
        PrintWriter out;
        s = null;
        try
        {
            s = new Socket(ip, port);
        }
        catch(UnknownHostException uhe)
        {
            logger.error("Host is unreachable with ip:port of [" + ip + ":" + port + "]", uhe);
            System.out.println("unknown exception occured :: hostis unreachable with ip:port"+ ip + ":" + port);
            s = null;
            return null;
        }
        catch(IOException ioe)
        {
        //My code will reach here .
            System.out.println("unable to connect with the port");
            logger.error("unable to connect with ip:port of [" + ip + ":" + port + "]", ioe);
            s = null;
            return null;
        }
    }

Please see my test class below

@PrepareForTest(MyClass.class)
    @RunWith(PowerMockRunner.class)
    public class MyClassTest{

    @Test
    public void test() throws Exception {
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PowerMockito.spy(MyClass.class);
        PowerMockito.doReturn(byteArrayOutputStream ).when(MyClass.class, "testMethod",Matchers.anyString(),Matchers.anyInt(),Matchers.<byte[]>any());
    }   
    }
Miller
  • 744
  • 3
  • 15
  • 39
  • show your test method, lets see the powermockito set-up – Maciej Kowalski Nov 17 '17 at 08:00
  • You have to mock the constructor call. Whereas the **better** answer is to look into dependency injection frameworks. Using `new` as you do not only makes your code hard to test, it also puts the burden of creating objects in the wrong place. – GhostCat Nov 17 '17 at 08:06
  • So, the other questions, in the end all tell you what you could have found in the documentation yourself: https://github.com/powermock/powermock/wiki/mockconstructor – GhostCat Nov 17 '17 at 08:08
  • @MaciejKowalski : I have added my test method – Miller Nov 17 '17 at 08:10
  • why are you mocking the method that you want to test? you should mock the new Socket(ip, port); creation and make assertions afterwards – Maciej Kowalski Nov 17 '17 at 08:12
  • @MaciejKowalski : Does I need to create a mock server for the same . I am doing unit testing for the first time . Any help will be highly appreciable – Miller Nov 17 '17 at 08:17
  • you also should not test private methods. You should probably refactor, create a specialized class with a public method and test that – Maciej Kowalski Nov 17 '17 at 08:19

0 Answers0