Hi,
I have this class that tries to mock a URL connection. It is a known example. Get an error.
java.lang.AssertionError: Wanted but not invoked java.net.URL(
"http",
"localhost",
80,
"POST"
);
Actually, there were zero interactions with this mock.
Thanks,
Mohan
public class TestPrintServer {
/**
* URL mock.
*/
private URL url;
/**
* HttpURLConnection mock.
*/
private HttpURLConnection connection;
private NettyServer instance = new NettyServer();
private ByteArrayInputStream input = new ByteArrayInputStream(
new Gson().toJson(
new PassBook()).getBytes() );
private ByteArrayOutputStream output = new ByteArrayOutputStream();
@Before
public void setUp() throws Exception
{
this.url = PowerMockito.mock(URL.class);
this.connection = PowerMockito.mock(HttpURLConnection.class);
PowerMockito.whenNew(URL.class).
withArguments( "http", "localhost", 80, "POST" ).thenReturn(this.url);
}
@Test
public void testDoPost() throws Exception
{
PowerMockito.doReturn(this.connection).when(this.url).openConnection();
PowerMockito.doReturn(this.output).when(this.connection).getOutputStream();
PowerMockito.doReturn(this.input).when(this.connection).getInputStream();
PowerMockito.verifyNew(URL.class);
final String response = this.instance.doPost("POST", new Gson().toJson(
new PassBook()));
// Mockito.verify(this.url).openConnection(); // cannot be verified (mockito limitation)
Mockito.verify(this.connection).getOutputStream();
Mockito.verify(this.connection).setRequestMethod("POST");
Mockito.verify(this.connection).setRequestProperty("Content-Type", "application/xml");
Mockito.verify(this.connection).setUseCaches(false);
Mockito.verify(this.connection).setDoInput(true);
Mockito.verify(this.connection).setDoOutput(true);
Mockito.verify(this.connection).getInputStream();
JsonParser parser = new JsonParser();
//assertEquals(this.output, input);
}
class PassBook{
private String name = "Test";
private double balance = 17989.99;
}
@Data class NettyServer{
private String doPost(String string, String input) throws MalformedURLException {
new URL("http", "localhost", 80, "POST");
return "{\"status\":1}";
}
}
}