Using Mockito to mock a local variable of a method

前端 未结 3 1340
走了就别回头了
走了就别回头了 2020-12-13 00:36

I have a class A that needs to the tested. The following is the definition of A:

public class A {
    public void methodOne(int arg         


        
3条回答
  •  遥遥无期
    2020-12-13 01:10

    You cannot mock a local variable. What you could do, however, is extract its creation to a protected method and spy it:

    public class A {
      public void methodOne(int argument) {
        //some operations
        methodTwo(int argument);
        //some operations
      }
    
      private void methodTwo(int argument) {
        DateTime dateTime = createDateTime();
        //use dateTime to perform some operations
      }
    
      protected DateTime createDateTime() {
        return new DateTime();
      }
    }
    
    public class ATest {
      @Test
      public void testMethodOne() {
        DateTime dt = new DateTime (/* some known parameters... */);
        A a = Mockito.spy(new A());
        doReturn(dt).when(a).createDateTime();
        int arg = 0; // Or some meaningful value...
        a.methodOne(arg);
        // assert the result
    }
    

提交回复
热议问题