Tutorial :Java Instantiate Abstract Class or Partially Implemented Interface



Question:

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?


Solution:1

example using EasyMock classextension framework

the class under test:

public class TestClass {   public boolean dir() {    return new File("/user/a.txt").exists();   }    

public boolean hasFiles() { return dir(); }}

Test:

  import static org.easymock.EasyMock.createMock;  import static org.easymock.EasyMock.expect;  import static org.easymock.EasyMock.replay;    

public class ATest { public static void main(String[] args) throws Exception { Class class1 = TestClass.class; TestClass mock = createMock(class1, class1.getMethod("dir")); expect(mock.dir()).andReturn(true).times(2); expect(mock.dir()).andReturn(false).times(2); replay(mock);

System.out.println("mock.dir()=" + mock.dir()); System.out.println("mock.hasFiles()=" + mock.hasFiles());

System.out.println("mock.dir()=" + mock.dir()); System.out.println("mock.hasFiles()=" + mock.hasFiles()); } }

output:

mock.dir()=true  mock.hasFiles()=true  mock.dir()=false  mock.hasFiles()=false


Solution:2

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.


Solution:3

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?


Solution:4

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?


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »