views:

110

answers:

4

I have an interface that has about 20 methods (huge).

I want to create a single instance for testing purposes, but I only need to override one method. What's a good way to get an instance of this class with the overridden method without having to define the whole class with a tone of "//TODO: implement this" methods.

Mocking frameworks might work too, but I might prefer something that uses refection. I can create a mock object, but then can I override the method in the mock object?

A: 

If you have sensible default behavior for all 20 methods, I'd recommend creating an abstract class that implements the interface. That's what the java.util API does. Check out java.util.List and java.util.AbstractList as an example.

duffymo
A: 

Use an IDE - they will add the missing implementation methods for you.

In eclipse, if you create class A implements I, there is a red mark at the top because you haven't implemented all the methods. You can then click (or right click, i forget) and it will offer to do it for you.

It will still have the todos, but who cares.

I have to say, your use case sounds a bit strange. Why are you only testing one method?

hvgotcodes
Presumably the OP is testing another component and needs a mock method argument -- which must be an instance of the 20-method interface thing.
@user268396 in that case, why not just mock? which he suggested but doesnt want to do because he wants one of the methods implemented. i think...
hvgotcodes
A: 

Either that or you could simply not worry about what is irrelevant to your test case. In this case it sounds like 19 out of 20 methods are not going to be called anyway, so why bother doing anything more than have the IDE/editor generate default method stubs?

+2  A: 
01