Hacker News new | past | comments | ask | show | jobs | submit login

That's quite an old fashioned way of testing exceptions, TestNG has allowed you to do the following since 2005:

    @Test(expectedExceptions = FooBarException.class)
    public void test() {
      thisShouldThrow();
    }
If the method doesn't throw or throws the wrong kind of exception, this test will fail.



That has the problem of separating the statement that is supposed to throw and then thrown exception. E.g. a slightly more complicated test case:

    @Test(expectedExceptions = FooException.class)
    public void test() {
      firstDoThis();
      thenThat();
      thenSomeMore();
      thisShouldThrow();
    }
Now you're only asserting that any of these statements throw, anywhere in the code under test. That's significantly weaker and I've seen it mask real problems in code.

I think using plain try something/fail/catch is clearer, or using Closures and an assertThrows if your language supports it.


You should probably think of splitting up your test case if it's this complicated.


You can always revert to the old try/catch/fail if you need to test something more complex (e.g. testing the message of the exception) but most of exception tests fall in the simple case shown above.


In that case, you first write a test case ensuring that the first three statements won't throw.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: