Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Butterknife to inject views in espresso Test clases in android?

Is it possible to use Butterknife to inject into view for a test class? The views are injected into a fragment that is created and committed by my MainActivity class.

Here is the code from my test class:

public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

private MainActivity mMainActivity;
private Button learnButton;
private Button teachButton;

@SuppressWarnings( "deprecation" )
public MainActivityTest() {
    super("com.example.application.app", MainActivity.class);
}

protected void setUp() throws Exception {
    super.setUp();

    mMainActivity = getActivity();
    learnButton = (Button) mMainActivity.findViewById(R.id.buttonLearn);
    teachButton = (Button) mMainActivity.findViewById(R.id.buttonTeach);
}

However I use Butterknife to inject the views in the my fragment:

public class ChooseActionFragment extends Fragment {

@InjectView(R.id.buttonTeach) Button buttonTeach;
@InjectView(R.id.buttonLearn) Button buttonLearn;

public ChooseActionFragment() { }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    ButterKnife.inject(this, rootView);
    return view;
}

I want to know how I could use Butterknife to reduce my boilerplate view code in my tests, just as I did in my production code.

like image 831
Andre Perkins Avatar asked Feb 23 '14 13:02

Andre Perkins


1 Answers

Yes, you can.

For reference: http://jakewharton.github.io/butterknife/javadoc/butterknife/ButterKnife.html

Include ButterKnife in you test dependencies.

The first argument of ButterKnife.inject() is the "target" i.e. an instance of the class with the @InjectView annotated fields and the second argument is an Activity, View or Dialog that contains the views to be injected.

Something like this:

public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

private MainActivity mMainActivity;
@InjectView(R.id.buttonLearn)
Button learnButton;

@InjectView(R.id.buttonTeach)
Button teachButton;

@SuppressWarnings( "deprecation" )
public MainActivityTest() {
    super("com.example.application.app", MainActivity.class);
}

protected void setUp() throws Exception {
 super.setUp();

  mMainActivity = getActivity();
  ButterKnife.inject(this, mMainActivity );
}
like image 89
yogurtearl Avatar answered Nov 09 '22 06:11

yogurtearl