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.log.LogUtil.CLog;
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(ITestInvocationListener)} call to a
32  * {@link Test#run(TestResult)} call.
33  */
34 public class JUnitRunUtil {
35 
runTest(ITestInvocationListener listener, Test junitTest)36     public static void runTest(ITestInvocationListener listener, Test junitTest)
37             throws DeviceNotAvailableException {
38         runTest(listener, junitTest, junitTest.getClass().getName());
39     }
40 
runTest(ITestInvocationListener listener, Test junitTest, String runName)41     public static void runTest(ITestInvocationListener listener, Test junitTest,
42             String runName) throws DeviceNotAvailableException {
43         if (junitTest.countTestCases() == 0) {
44             CLog.v("Skipping empty test case %s", runName);
45             return;
46         }
47         listener.testRunStarted(runName, junitTest.countTestCases());
48         long startTime = System.currentTimeMillis();
49         // forward the JUnit results to the invocation listener
50         JUnitToInvocationResultForwarder resultForwarder =
51                 new JUnitToInvocationResultForwarder(listener);
52         DeviceTestResult result = new DeviceTestResult();
53         result.addListener(resultForwarder);
54         try {
55             junitTest.run(result);
56         } catch (RuntimeDeviceNotAvailableException e) {
57             listener.testRunFailed(e.getDeviceException().getMessage());
58             throw e.getDeviceException();
59         } finally {
60             listener.testRunEnded(
61                     System.currentTimeMillis() - startTime, new HashMap<String, Metric>());
62         }
63     }
64 }
65