Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tests. Do I really need to add "throws Exception"?

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
}
like image 949
casper Avatar asked May 05 '14 14:05

casper


2 Answers

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

like image 104
Fredrik Avatar answered Oct 18 '22 20:10

Fredrik


junit 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());
    }
}
like image 4
Mureinik Avatar answered Oct 18 '22 19:10

Mureinik