ssacher-tgm / mockito

Automatically exported from code.google.com/p/mockito
0 stars 0 forks source link

Optional default answer RETURNS_SELF #201

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Recently, I wanted to mock a builder interface that gets used like this:

builder.addFoo(foo).addBar(bar).etc...

So I can verify the invocations on the interface. Having to stub out every 
method (a dozen in my case) in the interface just to return the mock object 
itself is a pain. RETURNS_MOCKS doesn't seem to return the same mock object for 
the interface.

Doesn't know enough Mockito internal to provide a patch. But this shouldn't be 
too hard for any one who does, right? ;)

Original issue reported on code.google.com by vic...@gmail.com on 24 Jun 2010 at 10:47

GoogleCodeExporter commented 8 years ago
Yo,

1. You can quite easily write an Answer that returns a mock by default, then 
pass this answer on mock creation.
2. Don't mock builders!!! :D It seems you should allow the real builder to 
create correct instance and then perform assertions on newly created instance. 
Seriously, have a look if your code cannot be refactored to be tested painlessly

Cheers!
Szczepan

Original comment by szcze...@gmail.com on 10 Jul 2010 at 12:56

GoogleCodeExporter commented 8 years ago
Thanks for the note, Szczepan!

1. The problem is that you cannot set a default answer after the mock is 
created. The workaround would be verifying on the first mock (in the answer) 
for later invocations, but it's ugly, which is usually not a word associated 
with mockito! It'll be really cool, if you can mock self ;)

2. Abstract builder pattern is commonly used in large system with non-trivial 
immutable objects. Having objects dependent on an abstract builder interface is 
fine. Using an arbitrary concrete builder for tests would be a violation of the 
spirit of unit tests and the Law of Demeter.

Original comment by vic...@gmail.com on 13 Jul 2010 at 12:46

GoogleCodeExporter commented 8 years ago
OK, got it, just return invocation.getMock() would work.

Thanks! Feel free to close the issue.

Original comment by vic...@gmail.com on 23 Jul 2010 at 1:50

GoogleCodeExporter commented 8 years ago
no probs ;)

Original comment by szcze...@gmail.com on 23 Jul 2010 at 2:17