在android中测试颜色类没有按预期工作

Iza*_*nus 5 java junit android gradle android-studio

我正在尝试为我的 android 应用程序中的 java 类编写测试用例,但它似乎没有按预期工作。

这是我的测试用例:

public void testGetColor() throws Exception {
    ShadesColor color = new ShadesColor(100, 200, 250);
    Assert.assertEquals(Color.rgb(100, 200, 250), color.getColor());

    Assert.assertEquals(100, color.getRed());
    Assert.assertEquals(200, color.getGreen());
    Assert.assertEquals(250, color.getBlue());
}
Run Code Online (Sandbox Code Playgroud)

以下是 ShadesColor 类。

public class ShadesColor {

    int color;

    public ShadesColor(int red, int green, int blue)
    {
        color = Color.rgb(red, green, blue);
    }

    public int getColor(){
        return color;
    }

    public ShadesColor interpolate(ShadesColor endColor, double percentage){
        int red = (int)(this.getRed() + (endColor.getRed() - this.getRed()) * percentage);
        int green = (int)(this.getGreen() + (endColor.getGreen() - this.getGreen()) * percentage);
        int blue = (int)(this.getBlue() + (endColor.getBlue() - this.getBlue()) * percentage);
        return new ShadesColor(red, green, blue);
    }

    public int getRed(){
        return Color.red(color);
    }

    public int getGreen(){
        return Color.green(color);
    }

    public int getBlue(){
        return Color.blue(color);
    }
}
Run Code Online (Sandbox Code Playgroud)

当调用 ShadesColor 构造函数时,颜色整数值始终为 0。由于默认情况下不会模拟 Android.Color,因此我在 build.gradle 文件中添加了以下行

testOptions {
    unitTests.returnDefaultValues = true
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

Bat*_*ark 2

我认为你正在进行本地单元测试,而不是 Android 仪器测试。本地单元测试没有真正的 Color 类,这就是您添加 unitTests.returnDefaultValues = true 的原因,这使得构造函数中的 Color.rgb(red, green, blue) 返回零。

模拟颜色类或使用另一个类。谢谢。