【问题标题】:How to avoid code duplication in a Android Test Application?如何避免 Android 测试应用程序中的代码重复?
【发布时间】:2011-09-28 20:06:02
【问题描述】:

假设我有一个应用程序,它具有类似的按钮,名为 button0、button1 等,直到 button9。

如何在不重复代码的情况下执行以下操作?

button0 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button0);
button1 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button1);
...
button9 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button9);

我尝试使用反射,但代码看起来不干净。

for (int i = 0; i <= 9; i++) {
    String btnName = "button" + i;
    /* do reflection stuff to link self.buttonX 
       with a reference to com.sample.SampleApp.R.id.buttonX */
}

【问题讨论】:

    标签: android unit-testing testing reflection junit


    【解决方案1】:

    以下代码未经测试,但请试一试:

    Button[] buttons = new Button[]{button0, button1, button2, button3, button4, button5, button6, button7, button8, button9};
    for (int i = 0; i < buttons.length, i++) {
       buttons[i] = (Button) findViewById(getResources().getIdentifier("button" + i, "id", "com.sample.SampleApp"));
    }
    

    使用 ArrayList(再次未经测试 - 只是为了让您了解我的意思):

    ArrayList<Button> buttons = new ArrayList<Button>();
    for (int i = 0; i < 10, i++) {
       buttons.add(new Button(this));
       buttons.get(i) = (Button) findViewById(getResources().getIdentifier("button" + i, "id", "com.sample.SampleApp"));
    }
    

    【讨论】:

    • 谢谢! getResources().getIdentifier() 会有很大帮助,但是有没有办法避免 Button 数组?
    • 我想您可以通过使用带有 Button 元素的 ArrayList 来稍微清理一下,但我认为您不会比这更“干净”。不过我很想被证明是错误的:)
    • ArrayList 根本没有帮助,但是您帮助我看到,如果我可以创建一个局部变量来引用 findViewById 找到的测试 UI 元素,我不需要实例变量来引用 UI 元素.谢谢。
    • 是的,现在我正在考虑它,ArrayList 可能是个坏主意。我不确定你是否能比第一个建议做得更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2016-08-07
    • 2011-08-29
    • 1970-01-01
    相关资源
    最近更新 更多