1

I am writing a JUnit test case for a method that has a getValue() method which returns an Object, the getValue() returns the value I pass inside setValue() and In this case when I pass a double value to setValue() it gives a class cast exception. I am not able to figure out how to fix this.

This is the if condition I am testing,

Public class ImageToolsMemento 
{
    public static final int FREEROTATION=3;
     private double _freeRotation;
    public void combine(ImageToolsMemento obj) //test method
    {
       if(((Integer)(obj.getValue(FREEROTATION))).intValue() != 0)//line 224
            _freeRotation = ((Integer)(obj.getValue(FREEROTATION))).intValue();
    }

public Object getValue(int type)
   {
     Object ret;
     switch(type)
     {
       case FREEROTATION:

       default:
         ret = null;
     }
     return ret;
   }

public void setValue(double value, int type)
  {
    switch(type)
    {
      case FREEROTATION:
          _windowPanelMemento.setValue(value, type);
          break;
      default:
            //"default case"
            break;
    }
 }
}

Test case

public class ImageToolsMementoTest 
{
    @InjectMocks
    ImageToolsMemento imageToolsMemento;

    @Before
    public void setUp() throws Exception 
    {
        imageToolsMemento=new ImageToolsMemento();
    }

   @Test
    public void testCombine() 
    {
      imageToolsMemento.setValue(1.3, ImageToolsMemento.FREEROTATION);
      imageToolsMemento.combine(imageToolsMemento);//calling test method, line 553
      double _freeRotation=Whitebox.getInternalState(imageToolsMemento, "_freeRotation");
        assertEquals(1.3,_freeRotation,0.0);
    }
}

Stack trace

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
    at com.toolboxmemento.ImageToolsMemento.combine(ImageToolsMemento.java:224)
    at com.toolboxmemento.test1.ImageToolsMementoTest.testCombine(ImageToolsMementoTest.java:553)

Can anyone please help me out with this problem P.S I cannot change the implementation

hushie
  • 417
  • 10
  • 23

2 Answers2

0

In java you cannot cast java.lang.Double to java.lang.Integer. Your error comes on line :

if(((Integer)(obj.getValue(FREEROTATION))).intValue() != 0)//line 224

Instead of cast you can use intValue method of Double class:

if(((Double)obj.getValue(FREEROTATION)).intValue() != 0)//line 224
Jay Smith
  • 2,331
  • 3
  • 16
  • 27
0

You need to perform explicit typecasting because double will not stored in int type implicitly.You can do this by : int i = (int) d;