Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Color class in android not working as expected

I am trying to write test cases for a java class in my android application, 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());
}

Following 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 gets called, the color integer value is always 0. Since Android.Color isn't mocked by default, I added the following line in my build.gradle file

testOptions {
    unitTests.returnDefaultValues = true
}

Am I missing something?

like image 218
Izaaz Yunus Avatar asked Oct 31 '22 00:10

Izaaz Yunus


1 Answers

I think you are doing a local unit test, not android instrumented test. Local unit test does not have a real Color class, which is the reason you added unitTests.returnDefaultValues = true, which makes Color.rgb(red, green, blue) in the constructor returns zero.

Mock Color class or use another class. Thanks.

like image 139
BattleShip Park Avatar answered Nov 15 '22 06:11

BattleShip Park