lundi 26 août 2019

Verify that a method of a regular (non-mock) object was called via reflection

I have code that looks like this:

abstract class Parent {
   public void dispatch(...) { ... }
}

The job of the dispatch method is to determine which method of the subclass should be called based on the value of the parameters, and then call it; this is done via runtime annotation analysis. So, if I have a subclass that looks like this:

class Child extends Parent {
    @CallThisMethodIfA
    public Thing aMethod(...) { ... }

    @CallThisMethodIfB
    public Thing bMethod(...) { ... }
}

then calling child.dispatch(A) should invoke aMethod (where child is an instance of Child). Of course, I'm simplifying as much as possible here - these aren't the actual annotations and args that I have.

My question is how to test this behavior. I tried something like:

Child child = new Child(...);
child.dispatch(A);
verify(child, times(1)).aMethod(...)

which gave me a NotAMockException because, of course, child is not a mock but a real object. I'm not 100% certain on how spying works, but I also tried instantiating Child using @Spy, and while that didn't throw an exception it also didn't register a call to aMethod because, I'm guessing, spying doesn't actually imitate the internal behavior of the class. How would I go about doing this? I guess I could manually initialize Child and make aMethod return a very specific instance of Thing that I can then check, but that doesn't feel clean to me (what if some other method just so happens to return an equal instance?)





Aucun commentaire:

Enregistrer un commentaire