Using attribute expected is a very weak solution because you have no control on which instruction of the method will throw the exception.
Even if I don't understand the reason of joining them... here there are some solutions:
JUNIT4
@Test
public void xyzAndPqr(){
try {
abc.pqr(null);
fail("pqr does not throw NullPointerException");
} catch(NullPointerException npe) {};
try {
abc.xyz(null);
fail("xyz does not throw NullPointerException");
} catch(NullPointerException npe) {};
}
NOTE: the catch takes only NullPointerException so if the methods throws other kind of exception the test correctly fails
NOTE1: in the catch clause you can check additional conditions (message, cause, etc)
NOTE2: the test fails at the first not correct method without checking the remaining. to check always all methods, you can use Collector Rule .
JUNIT5
import static org.junit.jupiter.api.Assertions.*;
@Test
public void xyzAndPqr(){
assertThrows(NullPointerException.class, () -> abc.pqr(null));
assertThrows(NullPointerException.class, () -> abc.xyz(null));
}
NOTE: assertThrows return the effective raised Throwable in the case you need to check additional conditions (message, cause, etc)
NOTE1: the test fails at the first not correct method without checking the remaining. to always check all methods, you can use AssertAll .
import static org.junit.jupiter.api.Assertions.*;
@Test
public void xyzAndPqr(){
AssertAll(
() -> assertThrows(NullPointerException.class, () -> abc.pqr(null)),
() -> assertThrows(NullPointerException.class, () -> abc.xyz(null))
);
}
JUNIT(both 4 and 5) with AssertJ
(see http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#exception-assertion)
import static org.assertj.core.api.Assertions.*;
@Test
public void xyzAndPqr(){
assertThatNullPointerException().isThrownBy( () -> abc.pqr(null) );
assertThatNullPointerException().isThrownBy( () -> abc.xyz(null) );
}
NOTE: you can use fluent syntax in assertJ: for example adding .withMessage("...")
NOTE1: the test fails at the first not correct method without checking the remaining. to check always all methods, you can use AssertAll (if in JUnit5) or assertJ soft assertions (in both cases)