【问题标题】:Unit Testing a GPS detecting method单元测试 GPS 检测方法
【发布时间】:2017-03-14 13:13:52
【问题描述】:

我真的需要对方法进行单元测试的帮助。我根本不明白该怎么做。当在我的 android 应用程序上按下以您的位置为中心的导航按钮时,将调用此方法。我们称之为 buttnav。

public void GPSDetector() { 
    AlertDialog.Builder build = new AlertDialog.Builder(
            mapFragment.getActivity());
    build
            .setTitle("GPS Detection Services")
            .setMessage("GPS is disabled in your device. Enable it?")
            .setCancelable(false)
            .setPositiveButton("Enable GPS",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(i);
                        }
                    });
    build.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog alert = build.create();
    alert.show();
}

地图片段是在片段内部的 onActivityCreated 上实例化为 SupportMapFragment 的实体:

mapFragment = (SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.map);

我很迷茫,找不到太多关于 Android 核心功能中单元测试的文档。我正在尝试使用 Junit。我尝试了 espresso,但它不包含 Android 核心功能视图。

【问题讨论】:

  • 欢迎来到 Stack Overflow!请拿起tour,环顾四周,并通读help center,尤其是How do I ask a good question?What topics can I ask about here?。 - UnitTests 单独测试一个单元的公共可观察行为 您必须重构代码以启用后者。
  • 我不明白如何以这种方式重构代码。你在某处有文档或一个非常好的网站吗?
  • 我可以推荐阅读:Robert C. Martin 的“清洁代码”和 Steve Freeman / Nat Pryce 的“Growing Object-Oriented Software, Guided by Tests”
  • 考虑先阅读众多关于单元测试的教程之一。正确编写的代码现在很难进行测试。

标签: java unit-testing android-studio junit junit4


【解决方案1】:

一开始:习惯Java Naming Conventions

方法名称以小写字母开头,最好以动词开头。


为了验证此方法的行为,您可以将AlertDialog.Builder 的实例替换为测试替身。您应该使用 mockito 之类的 mocking 框架 来创建一个。然后你必须重构你的代码,以便提供一个seam,你可以用测试替身替换真正的依赖。

有些人可能会建议 PowerMock(-ito),但我自己认为它的用户是对糟糕设计的投降。

如果不知道您的其余代码,我的建议是将AlertDialog.Builder 实例作为参数传递给您的方法。

【讨论】:

    猜你喜欢
    • 2014-06-07
    • 1970-01-01
    • 2021-12-15
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多