0
votes

I have an abstract class, say AbstractClass where I've got a public void method myMethod without an implementation. While I'm testing this class, I've created an anonymous subclass, where I can implement myMethod as I see fit. In AbstractClass There's another method, say myImplementedMethod which calls myMethod. Is there a trick to what I can put in myMethod in the anonymous subclass, so as to be able to verify that it has been called?

Edit: I'm using Mockito for mocking, and it is not my place to use another framework.

public abstract class AbstractClass {
    public abstract void myMethod();

    public void myImplementedMethod() {
        myMethod();
}

public class AbstractClassTest {

    @Before
    public void setUp() {
        AbstractClass myClass = new AbstractClass() {

            @Override
            public void myMethod(){
                //What could I put here?
            }
        }
    }

    @Test
    public void testMyImplementedMethod() {
        myClass.myImplementedMethod();
        //check that myMethod is called.
    }
}
4
Look at mocking frameworks. - SLaks
Oh, I'm using Mockito - kinbiko
Then check to make sure it's called. The subclass can't even compile if it doesn't exist. What specifically are you trying to test? - Dave Newton
How would I check that it's called? - kinbiko

4 Answers

2
votes

You could create a spy object on your descendant class, call the implemented method and later ensure the not implemented one was called with verify

AbstractClass myInstance= Mockito.spy(myClass);
myInstance.myImplementedMethod();
Mockito.verify(myInstance).myMethod();
2
votes
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

public class AbstractClassTest {

    private AbstractClass myClass;

    @Before
    public void setUp() {
        AbstractClass instance = new AbstractClass() {
            @Override
            public void myMethod(){}
        }
        myClass = spy(instance);
    }

    @Test
    public void testMyImplementedMethod() {
        myClass.myImplementedMethod();
        verify(myClass).myMethod();
    }
}
2
votes

If Mockito's spy works for you, great. However I don't believe it will capture internal method calls. How about the below...

public class AbstractClassTest {

 boolean methodCalled = false;

@Before
public void setUp() {
    methodCalled = false;
    AbstractClass myClass = new AbstractClass() {

        @Override
        public void myMethod(){
            methodCalled = true;
        }
    }
}

@Test
public void testMyImplementedMethod() {
    assertFalse(methodCalled);
    myClass.myImplementedMethod();
    assertTrue(methodCalled);
}
}
0
votes

can't you use the reflection api like this

YourClass.getClass().getMethod("myMethod").invoke(obj,args);  // pass the appropriate parameters

and if this throws an exception then you havent implemented the method. I didnt try this myself , if it works do comment .