Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can junit test that a method will throw an exception?

Could you tell me please, is it normal practice to write a method (example: JUnit Test) that throws an Exception, for example:

class A {
    public String f(int param) throws Exception {
        if (param == 100500)
            throw new Exception();
        return "";
    }
}

private A object = new A();

@Test
public void testSomething() throws Exception {
    String expected = "";
    assertEquals(object.f(5), expected);
}

In fact, method f() won't throw an exception for that parameter(5) but nevertheless I must declare that exception.

like image 794
Edison Miranda Avatar asked Nov 04 '14 14:11

Edison Miranda


People also ask

How do you test a method for exception in JUnit?

In order to test the exception thrown by any method in JUnit 4, you need to use @Test(expected=IllegalArgumentException. class) annotation. You can replace IllegalArgumentException. class with any other exception e.g. NullPointerException.

Can we throw exception in JUnit test?

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.

How can you use JUnit for testing a code that throws a desired exception?

JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation. Let us see @Test(expected) in action.

Which methods Cannot be tested by the JUnit test class?

Which methods cannot be tested by the JUnit test class? Explanation: When a method is declared as “private”, it can only be accessed within the same class. So there is no way to test a “private” method of a target class from any JUnit test class.


1 Answers

Yes it is completely fine, and if it does throw the exception the test will be considered as failed.

You need to specify that the method throws an Exception even if you know that the specific case does not (this check is done by the compiler).

In this case, what you expect is object.f(5) returns an empty string. Any other outcome (non-empty string or throwing an exception) would result in a failed test case.

like image 88
M A Avatar answered Sep 18 '22 17:09

M A