JUnit扩展方式(一)-使用Rule对JUnit进行扩展(JUnit4.10)

在上一篇文章中给出了JUnit4.8中如何使用Rule对JUnit进行扩展,在JUnit4.8中存在一个问题就是不能够使用Rule对于@BeforeClass和@AfterClass进行扩展,在JUnit4.10中JUnit提供了通过Rule对于@BeforeClass和@AfterClass扩展的方式;
在JUnit4.10中MethodRule被声明为过时的,建议使用TestRule替代,同时增加了@ClassRule的声明用于扩展@BeforeClass和@AfterClass
步骤:
1)创建一个新的Rule,该类实现TestRule接口;
2)在测试类中添加@Rule和@ClassRule用于扩展@Before@After和@BeforeClass@AfterClass;
代码如下:
LogRule用于扩展@BeforeClass和@AfterClass:
package extension;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class LogRule implements TestRule {

	@Override
	public Statement apply(final Statement statement, final Description target) {
		return new Statement() {
			@Override
			public void evaluate() throws Throwable {
				// extend @Before or @BeforeClass
				System.out.println("Before Class Rule: "
						+ target.getClassName());
				statement.evaluate();
				// extend @Before or @BeforeClass
				System.out
						.println("After Class Rule: " + target.getClassName());
			}
		};
	}

}

OperateRule用于扩展@Before和@After:
package extension;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class OperateRule implements TestRule {

	@Override
	public Statement apply(final Statement base, final Description des) {
		return new Statement() {
			@Override
			public void evaluate() throws Throwable {
				// Before method
				if (des.getAnnotation(BeforeMethod.class) != null) {
					System.out.println(((BeforeMethod) des
							.getAnnotation(BeforeMethod.class)).message());
				}
				base.evaluate();
				// After method
				if (des.getAnnotation(AfterMethod.class) != null) {
					System.out.println(((AfterMethod) des
							.getAnnotation(AfterMethod.class)).message());
				}
			}

		};
	}

}

测试用例类:
package test;

import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import extension.AfterMethod;
import extension.BeforeMethod;
import extension.LogRule;
import extension.OperateRule;

public class RuleTestCase {
	
	@ClassRule
	public static LogRule rule = new LogRule();
	
	@Rule
	public OperateRule rule2 = new OperateRule();

	@Test
	@BeforeMethod(message="test_1 before method")
	public void test_1() {
		System.out.println("test_1");
	}
	
	@Test
	@AfterMethod(message="test_2 after method")
	public void test_2() {
		System.out.println("test_2");
	}
	
	@Test
	@BeforeMethod(message="test_3 before method")
	@AfterMethod(message="test_3 after method")
	public void test_3() {
		System.out.println("test_3");
	}
}

执行结果如下:
JUnit扩展方式(一)-使用Rule对JUnit进行扩展(JUnit4.10)_第1张图片

你可能感兴趣的:(JUnit,JUnit4,Rule)