1 /* 2 * Copyright (C) 2011 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 package com.android.tradefed.testtype; 17 18 import com.android.tradefed.device.DeviceNotAvailableException; 19 import com.android.tradefed.metrics.proto.MetricMeasurement.Metric; 20 import com.android.tradefed.result.ITestInvocationListener; 21 import com.android.tradefed.result.JUnitToInvocationResultForwarder; 22 import com.android.tradefed.testtype.DeviceTestResult.RuntimeDeviceNotAvailableException; 23 24 import junit.framework.Test; 25 import junit.framework.TestResult; 26 27 import java.util.HashMap; 28 29 /** 30 * A helper class for directing a {@link IRemoteTest#run(ITestInvocationListener)} call to a 31 * {@link Test#run(TestResult)} call. 32 */ 33 public class JUnitRunUtil { 34 runTest(ITestInvocationListener listener, Test junitTest)35 public static boolean runTest(ITestInvocationListener listener, Test junitTest) 36 throws DeviceNotAvailableException { 37 return runTest(listener, junitTest, junitTest.getClass().getName()); 38 } 39 runTest(ITestInvocationListener listener, Test junitTest, String runName)40 public static boolean runTest(ITestInvocationListener listener, Test junitTest, String runName) 41 throws DeviceNotAvailableException { 42 if (junitTest.countTestCases() == 0) { 43 return false; 44 } 45 listener.testRunStarted(runName, junitTest.countTestCases()); 46 long startTime = System.currentTimeMillis(); 47 // forward the JUnit results to the invocation listener 48 JUnitToInvocationResultForwarder resultForwarder = 49 new JUnitToInvocationResultForwarder(listener); 50 DeviceTestResult result = new DeviceTestResult(); 51 result.addListener(resultForwarder); 52 try { 53 junitTest.run(result); 54 } catch (RuntimeDeviceNotAvailableException e) { 55 listener.testRunFailed(e.getDeviceException().getMessage()); 56 throw e.getDeviceException(); 57 } finally { 58 listener.testRunEnded( 59 System.currentTimeMillis() - startTime, new HashMap<String, Metric>()); 60 } 61 return true; 62 } 63 } 64