是否可以使用Butterknife注入测试类的视图?视图被注入到由MainActivity类创建和提交的片段中。
以下是我的测试类的代码:
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);
}
但是我使用Butterknife在我的片段中注入视图:
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;
}
我想知道如何在我的测试中使用Butterknife来减少我的样板视图代码,就像我在生产代码中所做的那样。
答案 0 :(得分:2)
是的,你可以。
供参考:http://jakewharton.github.io/butterknife/javadoc/butterknife/ButterKnife.html
在你的测试依赖项中加入ButterKnife。
ButterKnife.inject()的第一个参数是“目标”,即具有@InjectView注释字段的类的实例,第二个参数是包含要注入的视图的Activity,View或Dialog。
这样的事情:
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 );
}