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.
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With