6

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.

Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
Andre Perkins
  • 7,640
  • 6
  • 25
  • 39
  • In case you never got a solution for this, I ended up just using this code - https://stackoverflow.com/a/40496729/2480714 to obtain the Activity and then the standard `findViewById(R.id.my_view)` code to perform actions against the custom view. – PGMacDesign Mar 11 '19 at 19:25

1 Answers1

2

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 );
}
yogurtearl
  • 3,035
  • 18
  • 24
  • 1
    This doesn't work for me. I get NPEs every time I try to access any of the views. I've tried `ButterKnife.inject(this, activity);` and `ButterKnife.inject(this, fragment.getView())`. – psyren89 Oct 30 '14 at 02:23