dimanche 14 février 2016

Is it possible to mock a nested object that is accessed by reflection?

I need to mock an instance of RestRequest with Mockito in a way that this method would return for example "10.0.0.1".

  private static String getAddress(RestChannel channel) {
    String remoteHost = null;

    try {
      NettyHttpChannel obj = (NettyHttpChannel) channel;
      Field f;
      f = obj.getClass().getDeclaredField("channel");
      f.setAccessible(true);
      SocketChannel sc = (SocketChannel) f.get(obj);
      InetSocketAddress remoteHostAddr = sc.getRemoteAddress();
      remoteHost = remoteHostAddr.getAddress().getHostAddress();
      // Make sure we recognize localhost even when IPV6 is involved
      if (localhostRe.matcher(remoteHost).find()) {
        remoteHost = LOCALHOST;
      }
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
      e.printStackTrace();
      return null;
    }
    return remoteHost;
  }

Is this something feasible at all? I'd need to mock at least until the call to SocketChannel.getRemoteAddress(), where the socket channel is a private field accessed by reflection.





Aucun commentaire:

Enregistrer un commentaire