Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top