java - 单元 : How to write test case using jUnit and Mockito

标签 java unit-testing junit mockito

总的来说,我对 Mockito、jUnit 和 TDD 还很陌生,我尝试学习正确的 TDD 方法。我需要几个例子来启动我的大脑。所以请帮助我

所以我有一个方法 getNameInc(String dirPath, String filenName)。因此,给定一个类似 bankAccount.pdf 的文件名,如果在此文件夹中没有文件名 bankAccount.pdf,则返回 bankAccountAA.pdf。如果存在一个bankAccount.pdf,则返回bankAccountBB.pdf incrementAA-ZZ。当它到达 ZZ 时,它会回滚到 AA。我已经实现了这个方法的逻辑。如何使用 Mockiti 和 jUnit 对该方法进行单元测试?

编辑

这是涉及的类和方法。

public class PProcessor{

    private final Map<Integer, String> incMap = new HashMap<Integer, String>();

    private String getNameInc(String dirPath, String filenName){
         String[] nameList = new File(dirPath).list(new FilenameFilter(){
            public boolean accept(File file, String name) {
                //only load pdf files
                return (name.toLowerCase().endsWith(".pdf"));
            }
        });
        //Return the number of occurance that a given file name appear
        //inside the output folder.
        int freq = 0;
        for(int i=0; i<nameList.length; i++){

            if(fileName.equals(nameList[i].substring(0, 8))){
                freq++;
            }
        }
        return incMap.get(freq);
    }

    private void generateIncHashMap(){
        incMap.put(new Integer(0), "AA");
        incMap.put(new Integer(1), "BB");
        incMap.put(new Integer(2), "CC");
        ...
    }
}

generateIncHashMap() 将在构造函数中调用以预先生成 HashMap

最佳答案

我假设您正在尝试测试您的 getNameInc(..) 方法。当您调用它时,它会在您指定的目录中查找文件,并根据找到的内容修饰您给它的名称。

要使类可单元测试,您应该抽象对文件系统的依赖性,以便在 mock 中,您可以模拟您想要的任何目录内容。您的类将接受此接口(interface)的一个实例作为依赖项,并调用它来查找目录中的内容。当您在程序中实际使用该类时,您将提供此接口(interface)的实现,该接口(interface)委托(delegate)给 JDK 文件系统调用。当您对类进行单元测试时,您将提供此接口(interface)的 Mockito 模拟。

避免在 FilesystemImpl 类中放入太多逻辑,因为您无法为其编写严格的单元测试。让它成为文件系统的一个非常简单的包装器,这样所有智能的东西都在你的类中,你将为它编写大量的单元测试。

public interface Filesystem {
    boolean contains(String dirpath, String filename);
}

public class FilesystemImpl {
    boolean contains(String dirpath, String filename) {
        // Make JDK calls to determine if the specified directory has the file.
        return ...
    }
}

public class Yourmainclass {
    public static void main(String[] args) {

         Filesystem f = new FilesystemImpl();
         Yourclass worker = new Yourclass(f);
         // do something with your worker
         // etc...
    }
}

public class Yourclass {
    private Filesystem filesystem;

    public Yourclass(Filesystem filesystem) {
        this.filesystem = filesystem;
    }

    String getNameInc(String dirpath, String filename) {
       ...
       if (filesystem.contains(dirpath, filename) {
          ...
       }
    }

}

public class YourclassTest {

   @Test
   public void testShouldAppendAAWhenFileExists() {
       Filesystem filesystem = Mockito.mock(Filesystem.class);
       when(filesystem.contains("/some/mock/path", "bankAccount.pdf").thenReturn(true);
       Yourclass worker = new Yourclass(filesystem);
       String actual = worker.getNameInc("/some/mock/path", "bankAccount.pdf");
       assertEquals("bankAccountAA.pdf", actual);
   }

   @Test
   public void testShouldNotAppendWhenFileDoesNotExist {
       Filesystem filesystem = Mockito.mock(Filesystem.class);
       when(filesystem.contains("/some/mock/path", "bankAccount.pdf").thenReturn(false);
       Yourclass worker = new Yourclass(filesystem);
       String actual = worker.getNameInc("/some/mock/path", "bankAccount.pdf");
       assertequals("bankAccount.pdf", actual);
   }
}

由于测试之间有很多重复,您可能会创建一个设置方法并在那里做一些工作,并创建一些实例变量供测试使用:

    private static final String TEST_PATH = "/some/mock/path";
    private static final String TEST_FILENAME = "bankAccount.pdf";
    private Filesystem filesystem;
    private Yourclass worker;

    @Before
    public void setUp() {
        filesystem = Mockito.mock(Filesystem.class);
        worker = new Yourclass(filesystem);
    }

    @Test
   public void testShouldAppendAAWhenFileExists() {
       when(filesystem.contains(TEST_PATH, TEST_FILENAME).thenReturn(true);
       String actual = worker.getNameInc(TEST_PATH, TEST_FILENAME);
       assertEquals("bankAccountAA.pdf", actual);
   }

   etc...

关于java - 单元 : How to write test case using jUnit and Mockito,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6036650/

相关文章:

java - GWT:如何避免使用 i18n 常量指定默认属性文件

c# - 测试使用 HttpContext.Current.Request.Files 的 Web API 方法?

javascript - 使javascript函数回调-ish

node.js - vuejs组件单元测试中定义的 'this'变量如何获取

java - Gradle 无法使用 JavaFX 插件从 src/test 访问模块 src/main 中定义的类

java - java priorityQueue poll()方法的大O是什么

java - 如何更改未选定的 JavaFX ListCell 的背景颜色

java - Mockito 和 jUnit 用于使用 REST 模拟实用程序

java - 用接受字符串参数的构造函数实例化一个类对象?

kotlin - 一起运行时,测试会失败,但是单独运行会成功,即使在每次测试之前重新模拟实例