我如何为 android 片段 class 编写单元测试?

How can i write unittest for android fragment class?

我正在创建包含该片段的应用程序,为此我想使用

为其编写单元测试

Robolectric

代码如下

public class PlaybackFragment extends Fragment {

private CustomView customView;
private MyViewModel MyViewModel;

public static PlaybackFragment newInstance() {
    return new PlaybackFragment();
}

@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    initViews(view);
    initControllers();
    subscribeViewModel();
    loadData();
}

private void initViews(View view) {
    // init customView
}

private void initControllers() {
    // click events
}

private void subscribeViewModel() {
    //observer
}

private void loadData() {
    //load data for fragment
}   

}

那么,我该如何编写单元测试呢。

在您的 build.gradle 文件中添加 robolectric 依赖项:

testImplementation 'org.robolectric:robolectric:4.0'

步骤 1-在测试包中创建您的 Activity 测试 Class。

@RunWith(RobolectricTestRunner.class)
public class ActivityTest {

    private ActivityTest  activity;

    @Before
    public void setUp() {
        activity = Robolectric.setupActivity(ActivityTest.class);
    }

    @Test
    public void shouldNotBeNull() {
        assertNotNull(activity);
    }

    @Test
    public void shouldHaveWelcomeFragment() {
        assertNotNull(activity.getFragmentManager().findFragmentById(R.id.welcome_fragment));
    }
}

步骤 2- 创建片段测试 Class 以检查片段是否为 null

@RunWith(RobolectricTestRunner.class)
public class WelcomeFragmentTest {
    @Test
    public void shouldNotBeNull() {
        WelcomeFragment fragment = WelcomeFragment.newInstance();
        startFragment(fragment);
        assertNotNull(fragment);
    }
}