PowerMock比较强大, 是一个基于EasyMock之上的mock工具, 它可以帮你mock内部new的对象, final方法, 私有方法等等, 具体请看他的官网, 例子很详细
https://code.google.com/p/powermock/
我这边想mock httpclient 对象, 因为这个对象是在方法中被new出来的 jmock easymock无能为力
注意事项:
1. @PrepareTest (指的是你要测试的类)和 extends PowerMock一个不能少
2. replay(mockObj,mock.class) 必须这么写 ,mock.class 必须写实现类 不能写接口
3. PoolingConnectionManager与PowerMock有冲突,必须Mock
/**
* Date: 13-9-12
* Time: 上午10:44
*
* @author jack.zhang
*/
@PrepareForTest(UserResource.class)
public class UserResourceTest extends PowerMock{
private ClientConnectionManager connectionManager;
private UserResource resource;
@BeforeMethod
public void setup() {
resource = (UserResource) context.getBean("userResource");
connectionManager = (ClientConnectionManager) context.getBean("poolingClientConnectionManager");
}
@Test
public void testGetUser() throws Exception {
MockHttpRequest request = MockHttpRequest.get("user?method=user.type&user_id=100");
MockHttpResponse response = new MockHttpResponse();
DefaultHttpClient httpClientMock = createMockAndExpectNew(DefaultHttpClient.class, connectionManager);
expect(httpClientMock.execute(anyObject(HttpGet.class), anyObject(UserOrderCountResponseHandler.class))).andReturn(0).once();
replay(httpClientMock,DefaultHttpClient.class);
dispatcher.invoke(request, response);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
checkReturnValue(response.getContentAsString(), "b");
verify(httpClientMock);
}
}