Testing Color class in android not working as expected

I am trying to write test cases for a java class in my android app and it doesn't seem to work as expected.

This is my test case:

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());
}

      

Below is the ShadesColor class.

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);
    }
}

      

When the ShadesColor constructor is called, the integer color value is always 0. Since Android.Color is not mocked by default, I added the following line in the build.gradle file

testOptions {
    unitTests.returnDefaultValues = true
}

      

Did I miss something?

+4


source to share


2 answers


I think you are doing a local unit test, not an android instrument test. The local unit test has no real class Color, so you added unitTests.returnDefaultValues ​​= true, which makes Color.rgb (red, green, blue) null in the constructor.



Mock Color class or use another class. Thank.

+1


source


Use Robolectric

instead Mockito

. Run your test using@RunWith(RobolectricTestRunner.class)



0


source







All Articles