tags:

views:

27

answers:

2

hello,

my JUnit test is as follow :

public class Toto{
@BeforeClass
 public static void initTest1()
  {
try{
openAppli();
}catch(Exception e){
e.printStackTrace();
}
}
@Test
public void test1(){

try{
//do some actions
}catch(Exception e){
e.printStackTrace();
}

}
@AfterClass
public static void AfterTest1()
  {
    CloseAppli();

  }
}

I would like to know :

  1. is it the expected manner to write a JUnit test?
  2. should I call try/catch or throws ?
  3. could I call the same BeforeTest1() and AfterTest1() in other test class ?

thanks.

A: 

If you expect an exception to be thrown, you can annotate your Test with

@Test(expected=Exception.class)

for whatever Exception you are expecting.

If not, you can declare your test to throw an Exception.

DerMike
thanks, have you any answer for the other points please?
laura
A: 

In general, you shouldn't be catching the Exception base class. (This is sometimes known as "Pokemon exception handling" and unless you know exactly why you need to do it, it is bad practice.) Your unit tests should always be testing for a specific exception type if you expect an exception to be thrown, otherwise they may be passing when they shouldn't.

Remember that an exception means (or should mean) that your method can't do what its name says that it does. In your code itself, you shouldn't catch an exception unless you are certain that you know exactly what you need to do to recover from it.

jammycakes