Mocking OutputStream for HTTPUrlConnection.getOutputStream returns socketTimeoutException with Mockito

Viewed 24

I am trying to run mock a HttpUrlConnection call using Mockito and I am getting SocketTimeOutException when i hit the conn.getOutPutStream() in my code snippet below. I am already mocking OutputStream as showing in my test case...why am i still facing SocketTimeOutException?

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = "Strictness.LENIENT")
class MyServiceTest {

 @InjectMocks
 private MyService myService;

 @Mock
 HttpUrlConnection conn;



@Test
void testMyConn() {

String input = "foo";
OutputStream os = mock(OutputStream.class);
 
when(conn.getOutputStream()).thenReturn(os);
assertEquals("foo", myService.myConn(input));

}
}

This is my actual piece of code snippet which is failing in the try clause:

HttpUrlConnection conn = (HttpUrlConnection) myUrl.openConnection();
conn.setConnectTimeout(300000);
conn.setRequestMethod("POST");
try(OutputStream os = conn.getOutputStream()) {
//other logic

}

Need help in solving this thanks

0 Answers
Related