0

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?

xtofl
  • 40,723
  • 12
  • 105
  • 192
  • You want to not write `try/catch` and not declare a `throws` clause. That's simply not possible in java, you must handle checked exceptions somehow. Best and most common practice is the `throws` clause in test method signature. –  Jan 09 '13 at 22:51

2 Answers2

6

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.

Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171
-1

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
}
Dipak
  • 6,532
  • 8
  • 63
  • 87
  • 2
    nice, but that's not what I needed - rather something like `@Test (expected=NoException)`... – xtofl Jan 09 '13 at 11:48
  • Then just simply write down test case, do not write try catch. I think that would be fine. What do you think? Is there any problem with that? – Dipak Jan 09 '13 at 12:00
  • Java forces me to write a `throws` declaration. Now that you ask... I didn't mention that in the question. – xtofl Jan 09 '13 at 12:31
  • I think that means your source code function also had 'throws Exception' code, not handling it. Write try/catch in there and handle it well. – Dipak Jan 09 '13 at 12:40