Tests. Do I really need to add a “throw exception”?

I have seen people using throws Exception in tests, but I never do that. Should I worry? I have never had any problems with this. Who cares?

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

or

@Test()
public void test()
{
        //Do something
}
+4
source share
3 answers

will mark the test as being in an “error state” if an exception is thrown from this method. For most cases, this is essentially the same as rejecting a test (in the sense that a test that completed in an error state did not succeed). Many test authors do not like the problems (or code evasion) associated with handling checked exceptions.

, , :

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

, :

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

, , , - . " " , try-catch.

, , , . , - .

, , , .

+5

Functionally, there is no difference. This means that the compiler will not complain if you throw a RuntimeException. Since JUnit will catch any exception thrown by the test method, it doesn't really matter much anyway. However, it is generally believed that it is better to catch the Exception yourself and use the JUnit failure method, in which case you do not need the throws clause.

+3
source

Source: https://habr.com/ru/post/1539288/


All Articles