My JUnit test is as follows:
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:
- Is it the expected manner to write a JUnit test?
- Should I call try/catch or throws?
- Could I call the same BeforeTest1() and AfterTest1() in other test class ?
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.