Using Mockito to mock a local variable of a method

前端 未结 3 1339
走了就别回头了
走了就别回头了 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 00:50

    The best way to deal with such a problem is to use an injected Clock service, used to get new instances of DateTime. That way, your test can inject a mock Clock, which returns a specific DateTime instead of the current time.

    Note that the new Java 8 time API defines such a Clock class, specifically for that purpose.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-13 01:12

    Sorry for the late reply.

    This might be too much of a hassle, but if you mock the object that can give you the local variable, you can return a mock of it. I'd rather not restructure the code to make testing easier, but its something to consider.

    public class A {
    
        DateTimeFactory factory;
    
        private void method() {
            DateTime dateTime = factory.getDateTime();
            //use dateTime to perform some operations
        }
    }
    

    In your test you can do something like: when(factoryMock.getDateTime()).doReturn(dateTimeMock)

    The factory mock would need to be injected into the class somehow.

    0 讨论(0)
提交回复
热议问题