使用Mockito测试异常

时间:2016-10-25 00:54:17

标签: junit mockito

我有一个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循环中包含的条件)。< / p>

的Junit:

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()中测试这两个场景。如果文件不存在或者文件路径是目录,我希望抛出异常。

2 个答案:

答案 0 :(得分:1)

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

@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

答案 1 :(得分:1)

谢谢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