如何模拟测试方法中的局部变量

发布于 2025-01-31 14:07:14 字数 900 浏览 9 评论 0原文

我尝试了多种方法来模拟httpresponse(自定义类与任何库对象无关),但不是嘲笑。以下是我的代码。请建议如果错误。或其他任何回应的建议。

注意:我无法修改或编写任何工厂方法或我的myClass上的任何其他内容

Class MyClass{
 public void methodtoTest(ListOfObjects obj){
   HttpResponse response = null;
   response = HttpOperationHelper.executeHttpPostResponse(client, uri, heade, postBoday);
   if(response.getStatusCode() == 200){
     //some code is there
  }
}

httpoperationHelper是项目中的助手类,并且executehttpppoStrespResponse是静态方法。

@PrepareForTest(HttpOperationHelper.class)
Class MyClassTest{
  HttpResponse response = Mockito.mock(HttpResponse.class);
  response = HttpResponse.getInstance(200, "body");
  Powermockito.mockStatic(HttpOperationHelper.class);
  Mockit.when(HttpOperationHelper.executeHttpPostResponse(anyObject(), anyObject(), anyObject(), anyString())).thenReturn(response);
}

I have tried multiple ways to mock HttpResponse(custom class not related to any library) object but it's not mocking. Below is my code. please suggest if mistake. or any other suggestions to respond.

Note: I can't modify or write any factory method or any extra stuff on my MyClass

Class MyClass{
 public void methodtoTest(ListOfObjects obj){
   HttpResponse response = null;
   response = HttpOperationHelper.executeHttpPostResponse(client, uri, heade, postBoday);
   if(response.getStatusCode() == 200){
     //some code is there
  }
}

HttpOperationHelper is helper class in the project and executeHttpPostResponse is static method.

@PrepareForTest(HttpOperationHelper.class)
Class MyClassTest{
  HttpResponse response = Mockito.mock(HttpResponse.class);
  response = HttpResponse.getInstance(200, "body");
  Powermockito.mockStatic(HttpOperationHelper.class);
  Mockit.when(HttpOperationHelper.executeHttpPostResponse(anyObject(), anyObject(), anyObject(), anyString())).thenReturn(response);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文