3

My question is how mocks objects are created not how to create a mock object using a library.

I have looked at the Mockito library source code but I didn't understand how its done. I have searched in the Internet but the articles explain what are mock object and how to create them using libraries.

For dynamic programming language perhaps it's simple as we can change methods, variable but how its done in static programming language (Java for example)

Hunsu
  • 3,171
  • 7
  • 27
  • 59

1 Answers1

1

Let's begin with what a mock is: an object that you can set expectancies on it regarding methods that expects to be called, and/or parameters on those methods and/or count of calls on those methods.

Mocks are sent to tested objects in order to mimic certain dependencies without having to use the real code (in many cases this is problematic/dangerous, like dealing with payment gateways).

Since mocks will need to intercept calls to all (or some, in case of partial mocks) methods, there are several ways they can be implemented, depending mainly on the features the language provides. Particularly in Java this can be implemented via proxy classes: https://stackoverflow.com/a/1082869/1974224, an approach that kinda forces you (but in a good way) to use interfaces in your code when relying on dependencies.

Community
  • 1
  • 1
Cristik
  • 28,596
  • 24
  • 84
  • 120