Question

In google test, we have an

EXPECT_NO_THROW(x.foo());

How can I do this in JUnit? The thing I want to avoid is having to write a try/catch block, and to specify that my test function would throw anything. Java forces me to declare a throws clause with the test function...

Is it possible?

Was it helpful?

Solution

You don't need to. If your method throws an exception, the test will fail, which is what you want.

In this case, it's acceptable to have your test declaring throws Exception:

@Test public void testMe() throws Exception {
  x.foo();
}

This means (to me) that you're not expecting any exceptions.

OTHER TIPS

In Junit 4 we can use syntax like below to avoid try catch block.

@Test (expected=ExceptionClassName.class)
public void yourTestCase(){
      //testing codes
}

here you are expecting ExceptionClassName exception OR

if you are always expecting exception, of any kind can use it as

@Test (expected=Exception.class)
public void yourTestCase(){
      //testing codes
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top