The most common use case for mocking is
objA uses objB;
use objA without having objB populated/initialized
so that
@Mock
private UserInterface userInterface;
public void method() {
MockitoAnnotations.initMocks(this);
Client client;
client.setUserInterface(userInterface);
when(userInterface.getSomething()).thenReturn(new OutputType("f"));
client.doSomething();
}
But what if we actually need only OUTPUT of objA ?
Let say that we don’t want to call objA.doSomething(); that returns SomeOutput, to get SomeOutput, so we could
-
mock it for doSomething() to return SomeOutput; — doesn’t make much sense
-
populate a variable with
new SomeOutput(bla, bla, bla);without mocking anything at all.
I’m asking because I see programmers mocking the second way, which practically doesn’t make sense cause they just instantiate new SomeOutput(bla, bla, bla); and returns it via mocked objA;
Does it have any secret purpose ? I’m relatively new to mocking.
I don’t know if I got you but I’ll try to answer.
The goal of mocking (as you probably already know) is to isolate the piece of code you are testing. One unit test(I assume we are talking about unit test when there are mocking around)
should only test one thing. In your example you could do that :
even if the result is the same you will obtain mocking the object in this case you are not isolating the class you want to test because you are “calling” a dependent component code
Anyway I can suggest you to have a look at this book
http://artofunittesting.com/
even if it is in .net the concept are still the same