Search code examples
javareflectionfitnesseacceptance-testing

JAVA : know when a method is called


thinking of a weird problem in here. Say for example you have code deployed on your server which does the following:

//GET request called when a URL is hit
public void gETCalled(){
    MyClass.invoke();
}

Was wondering if its possible to know, from an external test class (which is deployed in the same server environment) on whether invoke() was ever called at all, without modifying MyClass ?

I am trying to write acceptance tests and was wondering if this was ever possible (without touching my MyClass code)


Solution

  • In terms of test cases, PowerMock can intercept static method calls.

    http://code.google.com/p/powermock/wiki/MockStatic

    However, from server side code, AoP (in particular aspectj) would be your best bet. That way you don't have to actually change any of your code (just code an aspect class), and you can enable it only when you want to adding in the aspectj weaver as a javaagent.

    The aspect would look something like this:

    @Aspect
    public class TrackMyClassInvoke {
        @Before("execution(* MyClass.invoke())")
        public void beforeInvoke() {
             // do something to track it here
        }
    }
    

    You'd need to make sure to include MyClass in your weaving (i won't get into the full process of weaving, as you can find that all on the aspectj site)

    http://www.eclipse.org/aspectj/