mardi 3 mai 2016

How to perform a simple injection of a mock object to my test class using Dagger and Mockito?

I have decided to use Dagger in order to manage my depencies in Android, however, I'm not able to perform a simple mock for the injected member in my unit tests. I'm not getting any error, I simply don't understand how the framework works and I've failled to find it in the docs. Here is what I have:

Clas I want to test:

@Inject
static DialogBuilder DIALOG_BUILDER;

public static void showErrorPopUp(Context context, String content) {
    DIALOG_BUILDER.getBuilder(context)
            .title(Html.fromHtml(...
}

Module for DialogBuilder:

@Module(
        staticInjections = {
                NotificationUtil.class
        }
)
public class UtilModule {

    private Context mContext;

    public UtilModule(Context context) {
        this.mContext = context;
    }

    @Provides
    @Singleton
    public DialogBuilder provideDialogBuilder() {
        return new DialogBuilder(this.mContext);
    }

}

Application class:

public class App extends Application {

    public static final String TAG = "App";

    private static App mApp = null;
    private static ObjectGraph objectGraph;

    @Override
    public void onCreate() {
        super.onCreate();
        this.mApp = this;
        objectGraph = ObjectGraph.create(getModules().toArray());
        objectGraph.injectStatics();
    }

    public static Context context() {
        return mApp.getApplicationContext();
    }

    public static void inject(Context context) {
        objectGraph.inject(context);
    }

    private List<Object> getModules() {
        return Arrays.<Object>asList(new ToolbarModule(), new UtilModule(App.context()));
    }

}

How do I inject a mock object for DIALOG_BUILDER from my test class? Thanks for the help :)

P.S.: I also haven't understand why the annotation @Component isn't working for me. Versions of Dagger I'm using are:

compile 'com.squareup.dagger:dagger:+'
provided 'com.squareup.dagger:dagger-compiler:+'

Aucun commentaire:

Enregistrer un commentaire