OptionIpChooser extends OptionSimpleChoice { public String detectIP() { String ip = null; GetMethod method = new GetMethod( URL ); String html; try { int statusCode = httpClient.executeMethod( method ); if ( statusCode != HttpStatus.SC_OK ) { LOG.error( "Could not fetch website to detect IP" ); return null; } byte[] responseBody = method.getResponseBody(); html = new String( responseBody ); } catch ( HttpException e ) { LOG.error( "Could not fetch website to detect IP" ); return null; } catch ( IOException e ) { LOG.error( "Could not fetch website to detect IP" ); return null; } finally { method.releaseConnection(); } Matcher m = PATTERN.matcher( html ); m.find(); ip = html.substring( m.start(), m.end() ); return ip; } OptionIpChooser( String name, String description, AbstractOptionVarchar url, AbstractOptionInteger port ); protected  OptionIpChooser( String name, String description, AbstractOptionVarchar url, AbstractOptionInteger port,
                               final HttpClient httpClient ); @Override void setSelectedAsString( String selected ); String detectIP(); static final String AUTO; static final String MANUAL; }
@Test public void testDetectIP() throws Exception { AbstractOptionVarchar url = new OptionSimpleVarchar( "URL", "value" ); AbstractOptionInteger port = new OptionSimpleInteger( "Port", 8080 ); HttpClient mock = createMock( HttpClient.class ); expect( mock.executeMethod( isA( HttpMethod.class ) ) ).andAnswer( new IAnswer<Integer>() { @Override public Integer answer() throws Throwable { HttpMethodBase httpMethod = (HttpMethodBase) (HttpMethod) getCurrentArguments()[0]; Field responseStreamField = HttpMethodBase.class.getDeclaredField( "responseStream" ); responseStreamField.setAccessible( true ); responseStreamField.set( httpMethod, new ByteArrayInputStream( expectedResponseBody.getBytes( "UTF-8" ) ) ); return HttpStatus.SC_OK; } } ); expectLastCall().times( 2 ); replay( mock ); OptionIpChooser ipChooser = new OptionIpChooser( "IP Chooser", "Test for IP Chooser", url, port, mock ); assertThat( ipChooser.detectIP(), is( IP ) ); String expectedUrl = String.format( "http: assertThat( url.getValue(), is( expectedUrl ) ); verify( mock ); }