如何模拟超类的最终方法

时间:2013-12-10 07:40:10

标签: mockito powermock

我想在AbstractHttpClient.java中模拟DefaultHttpClient.java和execute方法,DefaultHttpClient扩展AbstractHttpClient java类,而execute方法是final方法,所以我需要powermock来模拟final方法。

@RunWith(PowerMockRunner.class)
@PrepareForTest(DefaultHttpClient.class)
//@PrepareForTest(AbstractHttpClient.class)
public class RestClientTest {   
    DefaultHttpClient client;
    RestClient restClient = new RestClient();

    @Test
    public void getAll() throws Exception{
        client = PowerMockito.spy(new DefaultHttpClient());
            //PowerMockito.mock(DefaultHttpClient.class); 
            //Mockito.mock(DefaultHttpClient.class);
        HttpResponse response = PowerMockito.mock(HttpResponse.class);
        MarketplaceTO sampleData = new MarketplaceTO();
        sampleData.setName("name");
        //String endpoint = "";
        //ProtocolVersion protoCol = new ProtocolVersion("HTTP", 2, 1);
        //StatusLine status = new BasicStatusLine(protoCol, HttpStatus.SC_OK, null);
        //HttpResponse response = new BasicHttpResponse(status);
        BasicHttpEntity entity = new BasicHttpEntity();     
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(sampleData);
        oos.flush();
        oos.close();
        InputStream is = new ByteArrayInputStream(baos.toByteArray());
        entity.setContent(is);
        entity.setContentLength(is.available());
        response.setEntity(entity);
        //PowerMockito.doNothing().when((AbstractHttpClient)client).execute(Mockito.any(HttpUriRequest.class),Mockito.any(HttpContext.class));
        PowerMockito.doReturn(response).when(client).execute(Mockito.any(HttpUriRequest.class));
        //HttpGet getRequest = new HttpGet(endpoint);
        //PowerMockito.when(client.execute(Mockito.any(HttpGet.class))).thenReturn(response);
        //Mockito.stub(client.execute(getRequest)).toReturn(response);
        //System.out.println("code "+response.getStatusLine().getStatusCode());
        EMResponse<MarketplaceTO> responseData = restClient.getAll("", MarketplaceTO.class);
        //System.out.println("name is "+responseData.getModelObject().getName());
        Assert.assertEquals("name", responseData.getModelObject().getName());
    }
}

和RestClient.java有

public <T> EMResponse<T> getAll(String entity, Class<T> entityClass) {
        StringBuffer bufferedReader = null;
        String output = "";
        EMResponse<T> emResponse = null;
        EMError emError = null;
        ObjectMapper objectMapper = new ObjectMapper();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        try {
            bufferedReader = new StringBuffer();
            String endpoint = /*EntityManagerProperties
                    .get(EntityManagerProperties.ENTITY_MANAGER_SERVICE_URL)
                    + "/" + entity*/"http://google.com/abcd";
            HttpGet getRequest = new HttpGet(endpoint);
            HttpResponse response = httpClient.execute(getRequest);
            System.out.println("code "+response.getStatusLine().getStatusCode());
            return getEntityObjects(response, entityClass, true);
        } catch (ClientProtocolException e) {

            logger.error("Exception", e);

        } catch (IOException e) {

            logger.error("Exception", e);
        } finally {
            //httpClient.getConnectionManager().shutdown();
        }
        return emResponse;
    }

如果我在模拟执行方法后调用,那么它也调用实际方法。

请帮帮我。对不起我的英文。

1 个答案:

答案 0 :(得分:0)

调用原始执行方法的原因是因为您使用了构造函数

DefaultHttpClient httpClient = new DefaultHttpClient(); 
RestClient.java课程中

。 所以你应该模拟构造函数并返回你的模拟对象

  1. 添加此行

    whenNew(DefaultHttpClient.class).withNoArguments()thenReturn(客户端);

  2. 使用前:

    PowerMockito.doReturn(response).when(client)
                .execute(Mockito.any(HttpUriRequest.class));
    

    1. @PrepareForTest(DefaultHttpClient.class)更改为@PrepareForTest({DefaultHttpClient.class, RestClient.class})
    2. 这将解决您的问题。