android - 如何对 Android Studio 上的活动是否已更改进行单元测试
问题描述
我想测试将我重定向到另一个活动的方法“OnClick”是否有效。但我不知道如何在单元测试中做到这一点..
public void onClickManageServiceButton(View view){
Intent intent = new Intent(getApplicationContext(), ServiceManagement.class);
startActivity(intent);
解决方案
您可以使用Espresson Intents API轻松完成此操作:
在您的测试中,设置一个 IntentsTestRule 来记录被触发的意图。
@Rule public IntentsTestRule<MyActivity> intentsTestRule =
new IntentsTestRule<>(MyActivity.class);
在您的测试中,启动您的活动,触发被测方法,然后断言:
@Test
public void onClickManageServiceButton() {
// By default the rule launch your activity, so it's running by the time test starts
// Assuming the method to test is on your activity under test...
// You many need to find a View or mock one out to pass to the method.
mIntentsTestRule.getActivity().onClickManageServiceButton(null);
// Espresso will have recorded the intent being fired - now use the intents
// API to assert that the expected intent was launched...
Intents.intended(hasComponent(ServiceManagement.class.getName()));
}
检查Intents和IntentMatchers类参考,了解更多关于你可以做什么断言意图被触发。
希望有帮助!
推荐阅读
- java - Hibernate 未在新线程 {org.hibernate.exception.GenericJDBCException: could not extract ResultSet} 中从数据库加载数据
- javascript - 添加多个选中的默认值选择 2 jQuery 选择框
- c++ - 为什么 int arr[]={0,3,2,4,5,6,7}; 给出错误和 int arr[7]={0,3,2,4,5,6,7}; 不是
- .net-core - 读取 dotnet core 上的用户配置文件相关文件
- objective-c - iOS - 无法将 .MOV 和 .jpg 保存为 LivePhoto - 显示错误 NSCocoaErrorDomain Code=-1 [目标 C]
- docker - 为什么没有在 docker swarm 中运行的 kafka 端口?
- reactjs - 如何在渲染中调用方法而不是componentDidUpdate?
- android - 如何安全退出 Android Camera2BasicFragment 并在下一个活动中显示捕获的图像?
- scala - Spark小数类型精度损失
- python - 从 azure blob 存储中读取多行