0

I’m trying to write mocking for to set a simple set in a class. I know that we do not need mocking for this specific example. But I'm using this example to learn how to use the framework. class Test{ Integer value;

public Integer getValue(){
    return this.value;
}

public void setValue(int val){
    this.value = val;
}

}

my mocking method looks like:

@Test
public void  testSetMethod(){
    Test v = Mockito.mock(Test.class);
  
       Mockito.doCallRealMethod().when(v).setValue(10);
         assertEquals(10,v.getValue());
}

I’m getting zero for v.getValue() in my assetEquals method instead of 10.

MIKE
  • 95
  • 1
  • 3
  • 9
  • Why mocking at all? Why not simply test whether the `getValue` method returns the value that you provided in the `setValue` method one step before? – Seelenvirtuose Sep 25 '16 at 06:50
  • 2
    I need mocking for a more complicated scenario. But I'm just trying to learn how to use the framework. – MIKE Sep 25 '16 at 07:10
  • Then unfortunately your example is not well crafted. Please use your real scenario and reduce it to an [MCVE](http://stackoverflow.com/help/mcve). – Seelenvirtuose Sep 25 '16 at 07:11
  • Additionally, you should not ask on how to use a framework at SO. There are plenty of tutorials out there. – Seelenvirtuose Sep 25 '16 at 07:12
  • I'm not asking how to use the framework!!!! I said I'm learning how to use the framework. – MIKE Sep 25 '16 at 07:14
  • @MIKE your setValue does not return anything. Assuming that the method is void, look here http://stackoverflow.com/questions/2276271/how-to-make-mock-to-void-methods-with-mockito on how to mock void methods and if it is to return Integer then ```when(v.setValue(10)).thenReturn(new Integer(10));``` – Raf Sep 25 '16 at 07:16

1 Answers1

3

This line

Mockito.doCallRealMethod().when(v).setValue(10);

tells to call the real method when that method is called with that value.

So you have to call

v.setValue(10);

After that you would also have to add

 Mockito.doCallRealMethod().when(v).getValue();

to make your example work.

Janar
  • 2,623
  • 1
  • 22
  • 32