Ans*_*oid 31 android unit-testing android-fragments android-testing
在我以前的项目中,我通过活动完成了大部分工作,并根据文档使用了ActivityInstrumentationTestCase2:
http
://developer.android.com/tools/testing/activity_testing.html
我知道如何使用Activity Test Cases ; 但是当谈到Fragment时,我没有太多的想法,也没有找到与此相关的文档.那么当我有几个片段有一个或两个活动时,如何编写测试用例?任何示例代码或示例都会更有帮助.
Nac*_*chi 26
这是一个粗略的指南使用ActivityInstrumentationTestCase2:
第1步.创建一个空白活动来保存您的片段
private static class FragmentUtilActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout view = new LinearLayout(this);
view.setId(1);
setContentView(view);
}
}
Run Code Online (Sandbox Code Playgroud)
第2步:在测试中,实例化您的片段并将其添加到空白活动中
public class MyFragmentTest extends ActivityInstrumentationTestCase2<FragmentUtilActivity> {
private MyFragment fragment;
@Before
public void setup() {
fragment = new MyFragment();
getActivity().getFragmentManager().beginTransaction().add(1, fragment, null).commit();
}
}
Run Code Online (Sandbox Code Playgroud)
步骤3测试实例化的片段
@Test
public void aTest() {
fragment.getView().findViewById(...);
}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用robolectric,那么使用FragmentUtilTest类非常简单:
@Test
public void aTest() {
// instantiate your fragment
MyFragment fragment = new MyFragment();
// Add it to a blank activity
FragmentTestUtil.startVisibleFragment(fragment);
// ... call getView().findViewById() on your fragment
}
Run Code Online (Sandbox Code Playgroud)
AndroidX提供了一个库,FragmentScenario用于创建片段并更改其状态。
应用程序/build.gradle
dependencies {
def fragment_version = "1.0.0"
// ...
debugImplementation 'androidx.fragment:fragment-testing:$fragment_version'
}
Run Code Online (Sandbox Code Playgroud)
例子
@RunWith(AndroidJUnit4::class)
class MyTestSuite {
@Test fun testEventFragment() {
// The "fragmentArgs" and "factory" arguments are optional.
val fragmentArgs = Bundle().apply {
putInt("selectedListItem", 0)
}
val factory = MyFragmentFactory()
val scenario = launchFragmentInContainer<MyFragment>(
fragmentArgs, factory)
onView(withId(R.id.text)).check(matches(withText("Hello World!")))
}
}
Run Code Online (Sandbox Code Playgroud)
更多内容请参见官方文档。
| 归档时间: |
|
| 查看次数: |
20325 次 |
| 最近记录: |