Question

I saw people using "throws Exception" in tests, but I never do. Should I worry? I never had any issues with that. What's the difference?

@Test()
public void test() throws Exception
{
        //Do something
}

or

@Test()
public void test()
{
        //Do something
}
Was it helpful?

Solution 2

will mark a test as being in "error state" if an exception is thrown from that method. For most usecases, this is essentially the same as failing a test (in the sense that a test that completed in error state did not succeed). A lot of test authors don't like the hassle (or the code-uglification) associated with handling checked exceptions.

E.g., Consider a test that should run a couple of methods and assert the end state of an object:

public class SomeTest
    SomeObject so;

    @Before
    public void setUp() {
        so = new SomeObject();
    }

    @Test
    public void TestSomeFlow() {
        try {
            so.init();
        // must catch in order to avoid a compilation error
        } catch (InitExceptionIDontCareAbout e) {
            fail ("init failed");
        }

        try {
            so.doSomething();
        // must catch in order to avoid a compilation error
        } catch (SomeOtherExceptionIDontCareAbout e) {
            fail ("doSomething failed");
        }

        assertTrue ("doSomething didn't work", so.isSomethingDone());
    }
}

Now consider how much cleaner the code looks without exception handling:

public class SomeTest
    SomeObject so;

    @Before
    public void setUp() {
        so = new SomeObject();
    }

    // Any exception throwm will mean the test did not succeed
    @Test
    public void TestSomeFlow() throws Exception {
        so.init();
        so.doSomething();

        assertTrue ("doSomething didn't work", so.isSomethingDone());
    }
}

OTHER TIPS

If the code you are testing throws an exception, you must handle it in some way. Either by declaring a "throws Exception" in the method signature, or by using try-catch.

If the code you are calling in the method does not throw any exceptions, then you dont need either of those. The compiler will let you know if you need to catch an exception in some way.

Also note that you can do tests that makes sure an exception is thrown, see this answer

Functionally, there is no difference. It only means that the compiler wont complain if you throw a non-RuntimeException. Since JUnit will catch any exception thrown by the test method anyway, it does not really matter. However, it is usually considered a better practice to catch the Exception yourself and use the fail method of JUnit, in which case you do not need the throws clause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top