简体   繁体   English

Easymock:如何在没有可见性的情况下模拟对受保护方法的调用

[英]Easymock: How to mock call on protected method with no visibility

I am making a Rest call from my application using apache httpclient-4.0.1 which is all working fine until i am trying to create a unit test for this. 我正在使用apache httpclient-4.0.1从我的应用程序进行Rest调用,在我尝试为此创建单元测试之前,它们都工作正常。 I am using easymock and when i try to mock my DefaultHttpClient.execute(HttpUriRequest) i get the following error. 我正在使用easymock ,当我尝试模拟DefaultHttpClient.execute(HttpUriRequest) ,出现以下错误。

java.lang.IllegalStateException: missing behavior definition for the preceeding method call createHttpContext()

I have looked up the code and it appears that this method ( createHttpContext() ) is called on the execute(HttpUriRequest) method but it is a protected method so i have no visibility to it. 我已经查看了代码,似乎在execute(HttpUriRequest)方法上调用了此方法( createHttpContext() ),但它是protected方法,因此我无法看到它。

So how do you mock this call? 那么,您如何模拟这个电话?

In principle you should mock only the methods your SUT is invoking on its collaborators. 原则上,您应该只模拟SUT在其协作者上调用的方法。 If you need to mock something that is not directly invoked by your SUT then you are doing something wrong. 如果您需要模拟未由SUT直接调用的内容,则说明您做错了什么。

If the problem is you need to mock a static invocation there are several solutions. 如果问题是您需要模拟静态调用,则有几种解决方案。

  • Extract the static invocation to a different method in your SUT and test a partially mocked version of your SUT (mocking only the new method where the static invocation is done). 将静态调用提取到SUT中的其他方法,并测试SUT的部分模拟版本(仅模拟完成静态调用的新方法)。 Partial mocks using easymock 使用Easymock进行部分模拟
  • Use PowerMock and mock directly the static invocation. 使用PowerMock并直接模拟静态调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM