5

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?

2
  • what is ShadesColor? Commented Jul 2, 2015 at 6:50
  • ShadesColor is just a class that I created. Its a wrapper around the android Color class. Updated the question accordingly. Commented Jul 2, 2015 at 6:57

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Use Robolectric instead of Mockito. Run your test using @RunWith(RobolectricTestRunner.class)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.