0

I have this code in my MyClass.java : variable 'C' is the one added.

btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               final MyLocalClass mlc = new MyLocalClass(A, B, C);
          }
}

and I want to do Junit test like this: get the instance of 'mlc' then get the "C" in 'mlc' and compare.

    final Activity activity = getActivity();
    Field field = MyClass.class
            .getDeclaredField("mlc");
    field5.setAccessible(true);
    final MyLocalClassinstance = (MyLocalClass) field5
            .get(activity );

But error from OS:

junit.framework.AssertionFailedError: java.lang.NoSuchFieldExceptio

Could I get the instance of a local final variable?

Thank you very much.

AmyWuGo
  • 2,315
  • 4
  • 22
  • 26
  • It's not possible. See http://stackoverflow.com/questions/744226/java-reflection-how-to-get-the-name-of-a-variable . – Yam Marcovic Sep 19 '12 at 05:47
  • Thank you Yam Marcovic. Is there a way to get the top activity thread and get the value from that thread? Thank you. – AmyWuGo Sep 19 '12 at 05:56

1 Answers1

0

you cannot as explained by @Yam Marcovic.

but you can easiliy change the code to make it testable:

I would make mlc local to the Activity instead of local to the anonymous OnClickListener handling class like this

public class MyActivity : Activity {
    public MyLocalClass mlc; 
    public void Init() {
        btn.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                       mlc = new MyLocalClass(A, B, C);
                    }
        }
    }
}

this can be easily tested

MyActivity activity = (MyActivity) getActivity();   
// assert on activity.mlc.C
k3b
  • 14,517
  • 7
  • 53
  • 85
  • Thank you k3b, but I'm just responsible to the Junit test and there is no way to change the source. Anyway thank you. – AmyWuGo Sep 19 '12 at 07:02