0

As part of behavioral testing I need to simulate the method call in a given class.

So say if I have a class like:

class A {
public void abc(){
    new classB().getData();
}

public void xyz( boolean callabc){
    if (callabc) {
        abc();
    }
}

So my requirement is to first find all methods in class A then find which method is making which call like xyz is calling abc which is calling class B getData method.

Is it possible to get all these data in Java?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Madie
  • 231
  • 3
  • 10
  • 1
    Hmm... looks like you would want reflection - and I think it's too early for you to start learning about reflection. But I might be wrong. – RaminS Dec 11 '16 at 19:51
  • 2
    That is not valid java. Aside from not understanding the question. – f1sh Dec 11 '16 at 19:52
  • 1
    Reflection can get the methods. I'm not so sure about finding methods that call other ones – OneCricketeer Dec 11 '16 at 20:00
  • Thank you guys. Reflection is one thing I was trying too but I got stuck in one method calling other one. Especially when the call is going out of current class ( class A in my example). – Madie Dec 11 '16 at 20:07
  • Java does not provide information about methods called from code or any insight into the code of methods. Just that methods exist, their name and paramenter. However you can inspect the bytecode of a class (in any language, it's just a file format) and basically decompile code to get the required information. I guess it's really difficult and sometimes impossible since methods can be called via reflection and it's used to deliberately obfuscate method calls from such tools. – zapl Dec 11 '16 at 20:12
  • @zapl Another option would be to process the source code. – lexicore Dec 11 '16 at 21:48
  • @Madie This looks like a [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Explain (in detail) why you need this. – lexicore Dec 11 '16 at 21:51

1 Answers1

0

You can transform your code into something like this:

public class A {
    private final ClassB b;

    public A(ClassB b) {
        this.b = b;
    }

    public void abc(){
        b.getData();
    }

    public void xyz( boolean callabc){
        if (callabc) {
            abc();
        }
    }
}

Then you can pass mock implementation of class B during tests. Then you can verify that some method was invoked on mock with specific parameters with mockito library: http://static.javadoc.io/org.mockito/mockito-core/2.3.0/org/mockito/Mockito.html#1