使用.setText()

时间:2017-07-17 09:29:50

标签: android unit-testing

我尝试在我的android项目中对一个方法进行单元测试。 一切正常我试图在TextView上设置一个值。 是否可以跳过一行代码或者是否必须将其作为UI测试实现?

这是我尝试测试的方法:

public int compareEnteredValue(int batterySize, double valueFromEntry, double batteryArray[]) {
    int output = 0;
    for (int i = 0; i <= batteryArray.length - 1; i++) {
        if (valueFromEntry >= batteryArray[i]) {
            realChargeValue.setText((i * 5) + ""); // This is where the unit test fails
            output = i*5;
        }
        if (valueFromEntry < batteryArray[batteryArray.length - 1]) {
            realChargeValue.setText(R.string.hundredPercent);
            output = 100;
        }
    }
    return output;
}

2 个答案:

答案 0 :(得分:1)

你可以进一步分解它。这样你的单位就不会从里面设置文本。

public int compareEnteredValue(int batterySize, double valueFromEntry, double batteryArray[]) {
    int output = 0;
    for (int i = 0; i <= batteryArray.length - 1; i++) {
        if (valueFromEntry >= batteryArray[i]) {
            //realChargeValue.setText((i * 5) + ""); // This is where the unit test fails
            output = i*5;
        }
        if (valueFromEntry < batteryArray[batteryArray.length - 1]) {
            //realChargeValue.setText(R.string.hundredPercent);
            output = 100;
        }
    }
    return output;
}

然后你调用方法..

 int value = compareEnteredValue(....);
 if(value == 100)
    realChargeValue.setText(R.string.hundredPercent);
 else 
    realChargeValue.setText(value + "");

然后,您可以在没有setText问题的情况下测试该单元。

答案 1 :(得分:1)

添加@Doomsknight答案,通常不需要对代码的每一行进行单元测试。但是,如果你有足够的热情来测试甚至达到那个级别,那么你就可以实现它。我正在使用一些添加的接口来展示测试。

public class TestableClass{
    private UIElement realChargeValue;

    public TestableClass(UIElement uiElem){
        realChargeValue = uiElem;
    }

    public int compareEnteredValue(int batterySize, double valueFromEntry, double batteryArray[]) {
        //Your method which needs to test realChargeValue

        int output = 0;
        for (int i = 0; i <= batteryArray.length - 1; i++) {
            if (valueFromEntry >= batteryArray[i]) {
                realChargeValue.setText((i * 5) + ""); // This is where the unit test fails
                output = i*5;
            }
            if (valueFromEntry < batteryArray[batteryArray.length - 1]) {
                realChargeValue.setText(R.string.hundredPercent);
                output = 100;
            }
        }
        return output;
    }
}

public interface UIElement{
    boolean setText();
}

对于测试类,使用如下:

public class Test{
    @Test
    public void verify_compareEnteredValue_sets_correct_text(){
        ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
        UIElement dummyUIElement = mock(UIElement.class);
        doReturn(true).when(dummyUIElement).setText(argumentCaptor.capture());

        new TestableClass(dummyUIElement).compareEnteredValue();

        List<String> expectedValues = argumentCaptor.getAllValues();
        //do all asserts here over expectedValues
    }
}