Divya Jose
Divya Jose

Reputation: 389

Testing Exception using Mockito

I have a get file method which gives a file if the path provided to the method is present. If the file is not present, it will throw a 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;
}

I want to write a Junit test to check test that the method throws exception when the file does not exist and if the path is not a file but a directory(the conditions covered in the if loop).

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());
    }
}

The above Junit is what I have for now, however I think I am not doing the test right. I cannot understand how to test the two scenarios in the test method testGetFileThrowsException(). I want the exception to be thrown if file doesnot exist or if the file path is a directory.

Upvotes: 0

Views: 1287

Answers (2)

Divya Jose
Divya Jose

Reputation: 389

Thank you Slackmart. I tried a few things and this worked best for me.

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());
}

Thanks you @Slackmart

Upvotes: 1

slackmart
slackmart

Reputation: 4934

In order to test if the exception is thrown, I suggest you to use the TemporaryFolder JUnit class.

@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");
}

Remember the TemporaryFolder, File and Rule classes must be imported at the beginning of your test file:

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

For more info refer to the junit docs.

Upvotes: 1

Related Questions