lundi 6 juillet 2015

Creating a getTestContext() method with different access modifiers

I'm implementing a testing framework in Android, and I use some test files, so I'm using this way to be able to access these files. Everything worked fine at the beginning.

As I think this is useful and I'm going to use it in many test classes, I've created a superclass for all my test cases and added a getTestContext() method in it to use it via inheritance. And it doesn't work: I get a null value from the AndroidTestCase.getTestContext().

Doing tests with code in the same class, without inheritance, I've found the weird thing. This code works and returns the correct test context:

@Override
public void setUp() throws Exception {
  super.setUp();

  mTestContext = (Context) ServiceTestCase.class.getMethod("getTestContext").invoke(this);

  ...
}

private Context getTestContext() {
  return mTestContext;
}

But, if I change the method's visibility to public or protected, then the invoked method in setUp() returns null to the mTestContext attribute. This problemas happens only with this attribute and not with others.

I'm getting quite crazy looking for a reason to this. I don't know if it's an Android issue, or a reflection question, o a JUnit one, so I'd thank any help that may allow me continue investigating.

Aucun commentaire:

Enregistrer un commentaire