gpt4 book ai didi

java - 我如何为 android fragment 类编写单元测试?

转载 作者:行者123 更新时间:2023-12-02 01:13:59 26 4
gpt4 key购买 nike

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

为其编写单元测试

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 测试类。

@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 步-创建 Fragment 测试类以检查 Fragment 是否为 null

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

关于java - 我如何为 android fragment 类编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58931729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com