Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何使用Mockito模拟构造函数_Spring_Unit Testing_Mockito_Powermock_Powermockito - Fatal编程技术网

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
。该对象需要存在于类级别,以便您注入它。