вторник, 7 февраля 2012 г.

how to save static fields in android junit tests?

if you have "extends ActivityInstrumentationTestCase2" android junit tests then their static fields will be cleared out after each method run (if you call super.tearDown()), the problem is with android.test.ActivityTestCase#scrubClass()
protected void scrubClass(final Class<?> testCaseClass)
    throws IllegalAccessException {
        final Field[] fields = getClass().getDeclaredFields();
        for (Field field : fields) {
            final Class fieldClass = field.getDeclaringClass();
            if (testCaseClass.isAssignableFrom(fieldClass) && !field.getType().isPrimitive()) {
                try {
                    field.setAccessible(true);
                    field.set(this, null);
                } catch (Exception e) {
                    android.util.Log.d("TestCase", "Error: Could not nullify field!");
                }

                if (field.get(this) != null) {
                    android.util.Log.d("TestCase", "Error: Could not nullify field!");
                }
            }
        }
    }
-which is called from android.test.ActivityInstrumentationTestCase2#tearDown(). Just override it with empty method:
    @Override
    protected void scrubClass(Class testCaseClass) {
        // ignore
    }
-and you'll save your static variables!

Non static fields will be cleared by default JUnit implemention, so you should not get any regression issues here ))
p.s. +SO question

Комментариев нет:

Отправить комментарий