简体   繁体   中英

Is it possible to unit test a method which have setter and getter using mockito and powermock

I am writing unit test for a legacy code which is basically setting and getting value in the method using chain stub, the class I am testing does not have dependency on other classes so I do not have mock anything but have a method like this

public class SampleClass {
  public void process(Context context){
    context.getState().setValue(MathUtil.roundToThree(context.getState().getValue());
  }
}

The test class I have written is as follows:

@RunWith(MockitoJUnitRunner.class)
public class TestSampleClass{
 SampleClass sample = new SampleClass();
 @Test
 public void testProcess(){
 Context context = Mockito.mock(Context.class, Mockito.RETURNS_DEEP_STUBS);
 Mockito.when(context.getState().getValue()).thenReturn(4.12345);
 sample.process(context);
 assertEquals(4.123,context.getState().getValue(),0.0);
 }
}

Test case is failing because it is returing 4.12345 due to Mockito.when() but I am not sure how do I test the value in context object after calling the process() method.

I can not change the source code. Intializing Context is very difficult because it depends on so many other Classes. Please help.

The problem is that your stub State object doesn't know that the value returned by getValue() should be the last value that was passed to setValue() .

The stub created by Mockito doesn't automatically pick up that you have a getter and setter and the getter should return what the setter was last called with. It's just a dumb stub that only does what you've told it to do, and you haven't told it to do anything when setValue() is called.

It may be simplest to verify that setValue was called with the rounded value, rather than attempt to fetch it from getValue() :

    Mockito.verify(context.getState()).setValue(AdditionalMatchers.eq(4.123, 0.0));

Another approach is to create a test State class that has real getters and setters, and use that in your tests. Of course, whether or not you can do this depends on how many other methods this class has. If you were to write such a class (I named it TestState in the code below), the test code would look like the following:

@Test
public void testProcess2(){
    Context context = Mockito.mock(Context.class);
    Mockito.when(context.getState()).thenReturn(new TestState());
    context.getState().setValue(4.12345);
    sample.process(context);
    assertEquals(4.123,context.getState().getValue(),0.0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM