【问题标题】:Testing Exception using Mockito使用 Mockito 测试异常
【发布时间】:2017-03-06 21:35:38
【问题描述】:

我有一个 get file 方法,如果提供给该方法的路径存在,它会给出一个文件。如果文件不存在,它将抛出NullPointerException

public File getFile(String downloadFileName) throws Exception {
    File fileToUpload = new File(getFileLocation(downloadFileName));
    if(!fileToUpload.exists() && !fileToUpload.isFile()){
        throw new Exception("File not found");
    }
    return fileToUpload;
}

我想编写一个Junit 测试来检查该方法是否在文件不存在并且路径不是文件而是目录(if 循环中涵盖的条件)时抛出异常。

朱尼特:

public class KnewtonContentInventoryWokerTest {

    private HttpWorker httpHelper = mock(HttpWorker.class);
    private KnewtonContentInventoryWorker knewtonContentInventoryHelper;
    private MessageHandler messageHandler = spy(new MessageHandler(false));
    private String programNameString = "Realize Sample Program";
    private String completeResponse;
    private String filePath = "src/test/resources/Content_Inventory_testFile.xls" ;
    private String fileName = "Content_Inventory_testFile";
    private String fileDir = "src/test/resources/";
    private String jobIdRestPath = "";
    private String jobStatusRestPath = "";
    private String downloadExcelFileRestPath = "";
    private String uploadFileToS3RestPath = "";
    private File file = new File(filePath);

    @Before
    public void setup() throws Exception {
        setupWorker();

    }

    @Before
    public void setupWorker() {
        AuthContext authContext = new AuthContext();
        authContext.setAuthenticationDetails("/test/", "user", "pass", new HashSet<Cookie>());
        File file = new File("src/test/resources/Content_Inventory_testFile.xls");
        knewtonContentInventoryHelper = spy(new KnewtonContentInventoryWorker(authContext,programNameString, externalIds));
        knewtonContentInventoryHelper.messageHandler = messageHandler;
    }

    /**
     * Test the setting up method
     */
    @Test(expected = Exception.class)
    public void testGetFileThrowsException() throws Exception {
        doThrow(new Exception("")).when(knewtonContentInventoryHelper).getFile(anyString());
        knewtonContentInventoryHelper.getFile(anyString());
    }
}

上面的Junit 是我现在所拥有的,但是我认为我没有做正确的测试。 我无法理解如何在测试方法testGetFileThrowsException() 中测试这两个场景。如果文件不存在或文件路径是目录,我希望抛出异常。

【问题讨论】:

    标签: junit mockito


    【解决方案1】:

    为了测试是否抛出异常,建议你使用TemporaryFolderJUnit类。

    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder(); 
    
    @Test(expected=Exception.class)
    public void testGetFileThrowsExceptionIfDirectory() throws Exception {
        // The newFolder method will return a File object, so the fakeFolder
        // has a getPath() method, and we can pass that to your getFile method.
        File fakeFolder = tempFolder.newFolder('fakepath');
        knewtonContentInventoryHelper.getFile(fakeFolder.getPath());
    }
    
    @Test(expected=Exception.class)
    public void testGetFileThrowsExceptionIfFileDoesNotExists() throws Exception {
        File fakeFolder = tempFolder.newFolder('fakepath');
        tempFolder.newFile('fakepath/a.txt');
        // /tmp/junitRanDOMX219/fakepath/a.txt exists but not b.txt, so it should thrown the exception.
        knewtonContentInventoryHelper.getFile(fakeFolder.getPath() + "/b.txt");
    }
    

    记住 TemporaryFolderFileRule 类必须在测试文件的开头导入:

    import java.io.File;
    import org.junit.Rule;
    import org.junit.rules.TemporaryFolder;
    

    更多信息请参阅junit docs

    【讨论】:

      【解决方案2】:

      谢谢 Slackmart。 我尝试了一些东西,这对我来说效果最好。

      import org.mockito.Mockito;
      
      /*
       * test setup()
       */
      
      @Test(expected = Exception.class)
      public void testGetFileThrowsException() throws Exception {
          File mockedFile = Mockito.mock(File.class);
          Mockito.when(mockedFile.exists()).thenReturn(false);
          doThrow(new Exception("")).when(knewtonContentInventoryHelper).getFile(fileDir);
          knewtonContentInventoryHelper.getFile(anyString());
      }
      
      @Test(expected = Exception.class)
      public void testGetFileInvalidDir() throws Exception {
          File mockedFile = Mockito.mock(File.class);
          Mockito.when(mockedFile.isDirectory()).thenReturn(true);
          doThrow(new Exception("")).when(knewtonContentInventoryHelper).getFile(fileDir);
          knewtonContentInventoryHelper.getFile(anyString());
      }
      

      谢谢@Slackmart

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-23
        • 1970-01-01
        • 1970-01-01
        • 2023-01-25
        • 2017-06-27
        • 2013-02-15
        • 1970-01-01
        相关资源
        最近更新 更多