2

When in a test class we instruct mockito to providing some mock objects (annotating such attribute-fields with @Mock) for the purpose of the testing (maybe to be injected into @InjectMocks attribute-field), what are the rules being followed for creating each mock?

More specifically:

1) how is each mock being built?

2) how are the dependencies of each mock being handled? what rules and limitations should be considered when mocking?

3) The case "mocked class A depends on class B, and class B is in turn mocked (in the same test class)" is different from the case "mocked class A depends on class B and class B is not mocked"?

Johan
  • 3,561
  • 9
  • 29
  • 45

1 Answers1

5

The idea of mocks is exactly the opposite of what your question implies: they are not called by calling your constructors. That is the whole idea of mocks: they have nothing to do with your production code.

In other words: you ask for a mock object of some A.class; and you get an object that supports the methods of A.class. In that sense, a mocked A object doesn't have any dependencies.

You know, that is the whole point: if a mocked A would be the same as a real A; what sense would be in mocking?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Thanks. So all the dependencies of the mock object of some A.class are "null" ? What happens to the functionalities of the mock object if some dependency would be required not to be null? – Johan Jul 08 '16 at 11:09
  • 1
    Again: the mock doesn't depend on anything. It doesn't know or care what your class A needs to do its job. Because all its methods are completely bogus/fake: they have **nothing** to do with your production code. – GhostCat Jul 08 '16 at 11:18
  • So definitely if a test code does require at some point concrete implementations of an object, I would provide dependencies my self without using mocks for that object. Somehow mocking is not supposed to be always used. Am I right ? – Johan Jul 08 '16 at 11:30
  • 2
    The idea is: in order to test production code, you *might* have to control fields (or parameters) that your "class under test" will be using when you invoke a method to test something. When you need to control things, you typically turn to mocks. But assume you want to test a method foo that simply counts the number of keys starting with "A" of some map that is direcltly passed to foo. In that case you don't need a mock; to the contrary, you *want* to pass a real map here - which you carefully initialized before. So the answer: it depends. And seriously: **read** tutorials on this stuff. – GhostCat Jul 08 '16 at 11:35
  • 2
    As: stackoverflow is **not** programming school where other people **teach** you "complete methods". You really shouldn't get into that "and beyond that, please tell me this and that and how does it work over here" ... we help with specific problems; not with "I don't get the whole concept". – GhostCat Jul 08 '16 at 11:36