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());
}
}