简体   繁体   中英

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. I am using easymock and when i try to mock my DefaultHttpClient.execute(HttpUriRequest) i get the following error.

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.

So how do you mock this call?

In principle you should mock only the methods your SUT is invoking on its collaborators. If you need to mock something that is not directly invoked by your SUT then you are doing something wrong.

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). Partial mocks using easymock
  • Use PowerMock and mock directly the static invocation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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