package com.snail.example; import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.junit.Test; @RunWith(ExampleRunner.class) public class ExampleTest { /** ExampleRunner によって埋め込まれるはず. */ public String thisWillBeWeaved = null; // 成功するテスト @Test public void test1(){ System.out.println("test1()が呼ばれました"); assertEquals(0,0); } // 失敗するテスト @Test public void test2(){ System.out.println("test2()が呼ばれました"); assertEquals("Hello JUnit Runner World",thisWillBeWeaved); } // このメソッドは呼ばれないはず public void test3(){ System.out.println("test3()が呼ばれました"); assertEquals(0,1); } }
package com.snail.example; import java.lang.reflect.Field; import org.junit.internal.runners.statements.InvokeMethod; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; public class ExampleRunner extends BlockJUnit4ClassRunner { public ExampleRunner(Class<?> testClass) throws InitializationError { super(testClass); } @Override protected void runChild(FrameworkMethod method, RunNotifier notifier) { System.out.println("--▽--runChild()が呼ばれました--▽--"); super.runChild(method,notifier); System.out.println("--△--runChild()を終わります --△--"); } @Override protected Statement methodInvoker(FrameworkMethod method, Object test) { return new InvokeMethod2(method, test); } private class InvokeMethod2 extends InvokeMethod { private FrameworkMethod pTestMethod; private Object pTarget; public InvokeMethod2(FrameworkMethod testMethod, Object target) { super(testMethod, target); pTestMethod = testMethod; pTarget = target; } @Override public void evaluate() throws Throwable { System.out.println(pTestMethod.getName() + "の初期化処理を実行します"); try{ Field field = pTarget.getClass().getField("thisWillBeWeaved"); field.set(pTarget, "Hello JUnit Runner World"); }catch(Exception ignore){ ignore = null; } // テストメソッドの実行 super.evaluate(); System.out.println(pTestMethod.getName() + "の終了処理を実行します"); } } }
--▽--runChild()が呼ばれました--▽-- test1の初期化処理を実行します test1()が呼ばれました test1の終了処理を実行します --△--runChild()を終わります --△-- --▽--runChild()が呼ばれました--▽-- test2の初期化処理を実行します test2()が呼ばれました test2の終了処理を実行します --△--runChild()を終わります --△--
勿論どちらのテストも合格。ちゃんと thisWillBeWeaved? に "Hello JUnit Runner World" が設定されている。