Skip execution of a line using Mockito

Logic :

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 ?

Pavel Smirnov :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=150277&siteId=1