tags:

views:

326

answers:

5

My code takes an interface as input but only excercises a couple of the interface's methods (often, just getters).

When testing the code, I'd love to define an anonymous inner class that returns the test data. But what do I do about all the other methods that the interface requires?

I could use my IDE to auto-generate a stub for the interface but that seems fairly code-heavy.

What is the easiest way to stub the two methods I care about and none of the methods I don't?

+5  A: 

If you are using JUnit to test, use Mocks instead of stubs.

Read Martin Fowler's seminal article "Mocks Aren't Stubs"

I recommend the EasyMock framework, it works like a charm automatically Mocking your interface using reflection. It is a bit more advanced than the code samples in Fowler's article, especially when you use the unitils library to wrap EasyMock, so the syntax will be much simpler than that in the article. Also, if you don't have an interface, but you want to mock a concrete class, EasyMock has a class extension.

Justin Standard
+1  A: 

Check out JMock.

http://www.jmock.org/

Ben Hoffstein
A: 

Write an "Adapter Class" and overwrite only the methods you care.

class MyAdapter extends MyClass {
  public void A() {
  }
  ...
}
Burkhard
A: 

I believe the classical way is to make an abstract class with empty methods. At least, that's how Sun did for MouseListener, creating MouseAdapter to ease the use of these events.

PhiLho
A: 

EasyMock or JMock are definitely the winners. I haven't used JMock, but I know with EasyMock you can setup the Mock object according to a testing script and it will return certain values in certain situations or points during your test. It's pretty easy to learn and get running, generally in less than an hour.

Spencer K
JMock also do that.
marcospereira