Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bsharathchand/9890889afb6b27c5baac to your computer and use it in GitHub Desktop.
Save bsharathchand/9890889afb6b27c5baac to your computer and use it in GitHub Desktop.
Using ExpectedException Rule along with PowerMockRule in Junit 4

Using ExpectedException Rule with PowerMockRule in Junit 4

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.

  1. Set PowerMockRule using @ClassRule
  2. 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");
	}
}
@prettysnoopy
Copy link

But there will be an exception says "org.junit.internal.runners.rules.ValidationError: The @ClassRule 'rule' must implement TestRule". Since PowerMockRule is a MethodRule.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment