1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package vogar.target.junit; 18 19 import org.junit.internal.AssumptionViolatedException; 20 import org.junit.internal.runners.model.EachTestNotifier; 21 import org.junit.rules.TestRule; 22 import org.junit.runner.Description; 23 import org.junit.runner.notification.RunNotifier; 24 import org.junit.runner.notification.StoppedByUserException; 25 import org.junit.runners.ParentRunner; 26 import org.junit.runners.model.Statement; 27 28 /** 29 * Provides support for modifying the behaviour of {@link ParentRunner} implementations. 30 */ 31 public class ParentRunnerHelper { 32 ParentRunnerHelper()33 private ParentRunnerHelper() { 34 } 35 36 /** 37 * Runs a {@link Statement} that represents a leaf (aka atomic) test, allowing the test or 38 * rather a {@link TestRule} to abort the whole test run. 39 */ abortingRunLeaf( Statement statement, Description description, RunNotifier notifier)40 public static void abortingRunLeaf( 41 Statement statement, Description description, RunNotifier notifier) { 42 EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); 43 eachNotifier.fireTestStarted(); 44 try { 45 statement.evaluate(); 46 } catch (AssumptionViolatedException e) { 47 eachNotifier.addFailedAssumption(e); 48 } catch (StoppedByUserException e) { 49 // Stop running any more tests. 50 notifier.pleaseStop(); 51 52 // If this exception has a cause then the test failed, otherwise it passed. 53 Throwable cause = e.getCause(); 54 if (cause != null) { 55 // The test failed so treat the cause as a normal failure. 56 eachNotifier.addFailure(cause); 57 } 58 59 // Propagate the exception back up to abort the test run. 60 throw e; 61 } catch (Throwable e) { 62 eachNotifier.addFailure(e); 63 } finally { 64 eachNotifier.fireTestFinished(); 65 } 66 } 67 } 68