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