Reputation: 21981
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.
Upvotes: 1
Views: 577
Reputation: 26747
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 :
new SomeOutput(bla, bla, bla);
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
even if it is in .net the concept are still the same
Upvotes: 1
Reputation: 1504132
Mocking is great when you want to test interactions between components.
Stubs and fakes are great when you don't care about interactions, but you want one component to be able to provide data to another. These can end up taking longer to create initially than using a mocking framework, but then it's often easier to write further tests. Many mocking frameworks also provide stubbing capabilities.
For simple enough types (typically providing data rather than services) which have already been tested, just use the real types.
See Martin Fowler's articles on mocks and stubs for some more enlightenment.
Upvotes: 11