3

testInstrumentationRunner "com.example.theapp.utils.CustomAndroidJUnitRunner"在 Gradle 中设置Run/Debug Configurations -> Android Tests -> MyInstrumentedTest -> General -> Specific instrumentation runner (optional)并扩展后AndroidJUnitRunner

import android.app.Application;
import android.content.Context;
import android.support.test.runner.AndroidJUnitRunner;

public class CustomAndroidJUnitRunner extends AndroidJUnitRunner {
    @Override
    public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return super.newApplication(cl, className, context);
    }

    @Override
    public void callApplicationOnCreate(Application app) {
        super.callApplicationOnCreate(app);
    }
}

我设置了 BPnewApplicationcallApplicationOnCreate看到它callApplicationOnCreate被调用,但不是newApplication。可能是什么问题呢?

4

2 回答 2

0

在 android 27 的源代码中的 ActivityThread 的第 5732 行,您将看到以下内容,这解释了您看到这种行为的原因:

        // Do this after providers, since instrumentation tests generally start their
        // test thread at this point, and we don't want that racing.
        try {
            mInstrumentation.onCreate(data.instrumentationArgs);
        }
        catch (Exception e) {
            throw new RuntimeException(
                "Exception thrown in onCreate() of "
                + data.instrumentationName + ": " + e.toString(), e);
        }
        try {
            mInstrumentation.callApplicationOnCreate(app);
        } catch (Exception e) {
            if (!mInstrumentation.onException(app, e)) {
                throw new RuntimeException(
                  "Unable to create application " + app.getClass().getName()
                  + ": " + e.toString(), e);
            }
        }
于 2018-04-16T12:55:56.413 回答
0

我认为newApplication()没有被调用,因为断点没有被命中,但似乎在调试器有机会附加之前调用了该方法。

如果需要调试newApplication()方法,我建议添加Debug.waitForDebugger(); 在 Runner 构造函数中或断点之前的任何时间。否则使用其他一些标志来确定该方法是否被调用(即不要依赖调试器和断点)。

于 2017-09-11T21:58:20.010 回答