dimanche 31 janvier 2021

How to mock an object that is declared and created in the local scope of a method?

So I am unit testing a class(it extends from SourceTask in org.apache.kafka.connect.source.SourceTask) and this class needs to Mock some objects than interact with it to do unit testing, and I am doing so with EasyMock. The problem is that inside this class there is a method which makes an HTTP request to an URL, but the HttpUriRequest object is created and declared in the scope of the method(locally). Can I still mock this object although it is declared, created and used in the local scope of a method? If not, two possible solutions come to my mind:

  1. Create a local server which I can tweak to develop several test cases(now instead of mocking the HttpUriRequest I would be creating my own server so I can customize it to act as necessary in each test). But I do not know if this is correct for a unit test.
  2. Develop a Class that represents the connections to the server, I mean to extract all of the logic of the HTTP connections to another class that would be instantiated as an attribute in the class I am trying to test. This way I can now mock it easily. So may be my problem comes from a design mistake of my classes :/.

Aucun commentaire:

Enregistrer un commentaire