0
  • How are mock objects better than real objects in unit testing?

  • When you create a mock object, what exactly it means? For example let's say you create

    A a = Mockito.mock(A.class);

    Does it create an object of class A? or something else?

  • When you create a mocked object and use it in calling a method, say a.method1(), how does the mocked object knows that it should call method1 itself?

Kindly let me know about these.

NewLearner
  • 31
  • 8
  • 3
    Possible duplicate of [What is the purpose of mock objects?](http://stackoverflow.com/questions/3622455/what-is-the-purpose-of-mock-objects) – Nkosi May 30 '16 at 23:23

1 Answers1

1

What is a unit-test

A unit-test suggests you only want to see your functionality in a small environment, typically a class. But this class often talks to other classes and those talk to other classes... which can mean a lot of work, just to get this one class going. Also, you just want to test your unit. This is, where mocks/stubs come in. I will explain the distinction later.

What you do, is - instead of recreating your whole app - to make assumptions. A mock is basically an assumption. Everything your class needs, is being mocked or stubbed. This can also be the case for already tested parts of your unit. You assume, then you test one specific (real) part of your unit. Then mock this one, if necessary, and so on.

Now what is the difference between mocks and stubs.

Both are assumptions, but mocks are also expectations. So, if you use a mock, your testing-framework should complain, if it hasn't been used/called. A stub on the other hand, is just for the case. Like a random call to the Internet, lookups to database, which are not important for the test per se.

What your framework actually creates, depends on the framework and the language. But it will/should not call the original method, as explained above. Usually you'd have to tell this explicitly to the framework, which sometimes might make sense.

Andreas Gnyp
  • 1,106
  • 1
  • 14
  • 21