java - 如何使用mockito更改函数中的 boolean 值

标签 java mockito

这是我的类(class):

public class FileDeleter implements Deleter {

    public void deleteDirectories(List<GroupOfCountries> organizedCountries, String path) {
        List<String> listOfThreeLettersGroups = new ArrayList<String>();

        for (GroupOfCountries groupedCountries : organizedCountries) {
            listOfThreeLettersGroups.add(groupedCountries.getName()); //Here it's adding "ABC" and "PQR" to ArrayList because my countries are Albania, Belgium and Portugal.
        }

        for (String directoryToDelete : listOfThreeLettersGroups) { 
            String pathOfGorupDirectory = (path + File.separator + directoryToDelete); //Here it's creating paths to ABC and PQR directories, for example /home/test/ABC
            File tempfile = createFile(pathOfGorupDirectory);
            deleteDirectory(tempfile);
        }
    }

    protected File createFile(String pathOfGorupDirectory) {
        return new File(pathOfGorupDirectory);
    }

    private boolean deleteDirectory(File dir) {
        if (dir.isDirectory()) {
            File[] children = dir.listFiles();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDirectory(children[i]);
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
}

我想要 100% 错过分支。如果我评论这些行:

if (!success) {
   return false;
}

我 100% 错过了分支。但是有人知道我可以使用mockito/junits 将 success 变为 false 做什么?因为 success 总是返回 true,所以这种情况永远不会发生。

最佳答案

也许这会有所帮助。

FileDeleter deleter = Mockito.mock(FileDeleter.class);
Mockito.when(deleter.deleteDirectory(Mockito.any())).thenReturn(false);

关于java - 如何使用mockito更改函数中的 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32048290/

相关文章:

java - 为什么 ModelAtribute 作为 null 传递?

java - Mockito 在测试方法之外 stub

java - 在右键单击上下文菜单中添加一个条目,从而运行一个 java 程序

java - hibernate :ClassCastException

java - 如何使用 astyanax 在 Cassandra 中设置 GCGraceSeconds?

java - 如何使用具有特定属性的参数对方法进行 stub

java - 模拟 Vertx.io 异步处理程序

JavaFX8 DatePicker 按钮大小改变

java - Spring MVC 使用不同的 HTTP 方法转发到 Controller

java - AEM - 用于查询生成器的 JUnit 测试用例