When using PowerMockRule for running the tests with PowerMockRunner then ExpectedExeption rule will not actually catch the exceptions, but throws it as an error. Inorder to make this work we will need to do this actions.
- Set PowerMockRule using @ClassRule
- Set ExpectedException using @Rule
Example code given below.
package test.com.novicehacks.autobot.learning.ssh;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.powermock.modules.junit4.rule.PowerMockRule;
public class TestExpectedExceptionRule {
@ClassRule
public static PowerMockRule rule = new PowerMockRule ();
@Rule
public ExpectedException exception = ExpectedException.none ();
@Test
public void testExcepiton() {
exception.expect (NullPointerException.class);
exception.expectMessage ("Image is null");
throw new NullPointerException ("Image is null");
}
@Test
public void testExcepitonWithPowerMockRule() {
exception.expect (NullPointerException.class);
exception.expectMessage ("Image is null");
throw new NullPointerException ("Image is null");
}
}
But there will be an exception says "org.junit.internal.runners.rules.ValidationError: The @ClassRule 'rule' must implement TestRule". Since PowerMockRule is a MethodRule.