Spring 如何使用Mockito模拟构造函数
我有一门课是这样的:Spring 如何使用Mockito模拟构造函数,spring,unit-testing,mockito,powermock,powermockito,Spring,Unit Testing,Mockito,Powermock,Powermockito,我有一门课是这样的: public class A { public Integer callMethod(){ return someMethod(); } private Integer someMethod(){ //Some Code HttpPost httpPost = new HttpPost(oAuthMessage.URL); //Some Code HttpClient httpClient = new DefaultHttpClient();
public class A {
public Integer callMethod(){
return someMethod();
}
private Integer someMethod(){
//Some Code
HttpPost httpPost = new HttpPost(oAuthMessage.URL);
//Some Code
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost); ------1
Integer code = httpResponse.getStatusLine().getStatusCode(); ---2
return code;
}
现在我想模拟第1行和第2行并返回一个模拟的HttpResponse和代码
我尝试过这一点,但失败了:
@RunWith(MockitoJUnitRunner.class)
public class TestA {
//Spying some things here & Injecting them
@Test
public void testA() {
HttpResponse httpResponse = Mockito.mock(HttpResponse.class, RETURNS_DEEP_STUBS);
HttpClient httpClient = Mockito.mock(HttpClient.class);
HttpPost httpPost = Mockito.mock(HttpPost.class);
Mockito.doReturn(httpResponse).when(httpClient).execute(httpPost);
Mockito.when(httpResponse.getStatusLine().getStatusCode()).thenReturn(anyInt());
//call the method
}
但这是行不通的。谁能告诉我一些想法吗?
谢谢。这是实现目标的方法,了解您的问题更多的是您正在创建不稳定的代码。是的,Powermock可以提供帮助;但是更好的方法是编写更多的可测试代码。请参见此处了解什么方法:实际回答它为什么不起作用:如果您模拟
HttpClient
,这并不重要,因为就在您标记为1
的行之前,您创建了一个“新的”HttpClient
。该对象需要存在于类级别,以便您注入它。是实现目标的方法,了解您的问题更多的是您正在创建不稳定的代码。是的,Powermock可以提供帮助;但是更好的方法是编写更多的可测试代码。请参见此处了解什么方法:实际回答它为什么不起作用:如果您模拟HttpClient
,这并不重要,因为就在您标记为1
的行之前,您创建了一个“新的”HttpClient
。该对象需要存在于类级别,以便您注入它。