2

I am using mockito for unit testing and I want to skip a line.

// method I am testing
public String doSomeTask(String src, String dst) {
    // some code

    utils.createLink(src,dst);

    // some more code
} 


// utils class
public void createLink(String src, String dst) {
    // do something
    Path realSrc = "/tmp/" + src;
    Files.createSymbolicLink(realSrc, dst);

    // do something
}


// Test class

@Mock
private Utils utils;

@Test
public void testDoSomeTask() {
    // this does not seem to work, it is still executing the createLink method
    doNothing.when(utils).createLink(anyString(), anyString());
    myClass.doSomeTask(anyString(), anyString());
}

Now, createLink is a void method and its failing during my testing with exception reason AccessDenied to create a directory.

I want to skip the line utils.createLink(src,dst); and continue with next lines. Is there a way I can tell Mockito to do this ?

Logic
  • 2,230
  • 2
  • 24
  • 41

2 Answers2

2

Assuming that utils variable can be set with a setter, you can spy on your Utils class object and override its createLink() method.

The basic idea is:

Utils utils = new Utils();
Utils spyUtils = Mockito.spy(utils);
doNothing().when(spyUtils).createLink(any(String.class), any(String.class));

Now, set this spyUtils object via setter. Each time createLink is invoked, it does nothing.

Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
0

You can either mock you utils method to do nothing (with PowerMockito) or change you code so utils method is not static and you can inject the mock instance of utils method to the object you test, something like this:

class ForTesting{

     UtilsClass utilsInstance;

      ForTesting (UtilsClass utilsInstance) {
        this.utilsInstance = utilsInstance;
      }

     // method you test
      public String doSomeTask(String src, String dst) {
         // some code
             utilsInstance.createLink(src, dst);
          // some more code
      } 
   }

 @Test
 public void test(){
     UtilsClass utilsInstance  = mock(UtilsClass.class);
     ForTesting classForTesting = new ForTesting(utilsInstance);
     assertEquals("yourValue",classForTesting.doSomeTask());

 }

Mocking with PowerMockito gives some overhead, because you cant override static methods without inheritance, so some native methods needed to modify byte code at runtime.

ipave
  • 1,249
  • 9
  • 17