0

I'm using JUNIT 4.7 using maven

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.7</version>
    </dependency>

I have my method for uploading a file and I'm using my own userdefined exceptions as below

public void uploadFile(String fileName) {
    File file  = null;

    try {
        file = new File(DIR + "/" + fileName);

        // If the file size exceeds 10 MB raise an exception
        if ((file.length() / MB) > 10)
            throw new FileSizeExceedLimitException("File size should not exceed 10 MB");

        else {
            System.out.println("File Uploaded Successfully");
        }
    } catch (FileSizeExceedLimitException e) {
        e.printStackTrace();
    }
}

And my User defined exceptions looks like below

public class FileSizeExceedLimitException extends Exception{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public FileSizeExceedLimitException(String s){
        super(s);
    }
}

And my Test cases are looks like below

Method 1 :

DocxOperations operations = null;

@Rule
public final ExpectedException exception = ExpectedException.none();

@Before
public void before() {
    operations = new DocxOperations();
}

@Test
public void testUploadFileSize() {
    exception.expect(FileSizeExceedLimitException.class);
    operations.uploadFile("Bigdata.docx");
}

Method 2 :

@Test(expected = FileFormatException.class)
public void testUploadFile() {
    operations.uploadFile("01 Big Data Hadoop Intro V 2.0.docx");
}

Method 3 :

@Test(expected = FileFormatException.class)
public void testUploadFile() throws FileFormatException{
    operations.uploadFile("01 Big Data Hadoop Intro V 2.0.docx");
}

In all the above methods i'm unable to pass the test cases,and i have seen these solutions but they are not useful for me

Assert Exception, Testing Exception

In my main code i.e in uploadFile method i have to use only try, catch not throws

Community
  • 1
  • 1
Manoj Kumar
  • 745
  • 2
  • 8
  • 29

1 Answers1

1

The problem is you aren't throwing the exception beyond your method call:

Here is the simplifed code with just the throw and catch to see it more clearly

try {
   ...

        throw new FileSizeExceedLimitException("File size should not exceed 10 MB");
    ...

  } catch (FileSizeExceedLimitException e) {
    e.printStackTrace();
}

You are catching and swallowing the exception. Remove the try-catch and make your method throws FileSizeExceedLimitException and the test should work

dkatzel
  • 31,188
  • 3
  • 63
  • 67
  • thanks for answering, but In my main code i.e in `uploadFile` method i have to use only `try`, `catch` not `throws` – Manoj Kumar Nov 19 '15 at 17:13