'Skip execution of a line using Mockito
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 ?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ipave |
