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,281
  • 7
  • 29
  • 64
  • It depends. Anything from [cglib](https://github.com/cglib/cglib) to dynamically create classes to a [`Proxy`](https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html). This question is too broad. – Boris the Spider Apr 05 '15 at 10:31
  • I am really not sure what do you mean by Java as a dynamic language. – thefourtheye Apr 05 '15 at 10:32
  • Yes, can you define what the difference between a static and dynamic language is? – Boris the Spider Apr 05 '15 at 10:36
  • Actually static languages methods are harder to stub/mock then dynamic language ones. And you didn't just say that Java is dynamic, did you? :) – Cristik Apr 05 '15 at 10:42

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
  • 30,989
  • 25
  • 91
  • 127