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 package android.support.v7.recyclerview.test; 17 18 import android.support.test.rule.ActivityTestRule; 19 import android.support.v7.widget.TestActivity; 20 21 import org.junit.runner.Description; 22 import org.junit.runners.model.Statement; 23 24 /** 25 * Like ActivityTestRule but re-uses the same activity 26 */ 27 public class SameActivityTestRule extends ActivityTestRule<TestActivity> { 28 static TestActivity sTestActivity; 29 public SameActivityTestRule() { 30 super(TestActivity.class, false, false); 31 } 32 33 public boolean canReUseActivity() { 34 return true; 35 } 36 37 @Override 38 public Statement apply(final Statement base, Description description) { 39 return new ReUsedActivityStatement(base); 40 } 41 42 @Override 43 public TestActivity getActivity() { 44 if (sTestActivity != null) { 45 return sTestActivity; 46 } 47 return super.getActivity(); 48 } 49 50 private class ReUsedActivityStatement extends Statement { 51 52 private final Statement mBase; 53 54 public ReUsedActivityStatement(Statement base) { 55 mBase = base; 56 } 57 58 @Override 59 public void evaluate() throws Throwable { 60 try { 61 if (sTestActivity == null || !sTestActivity.canBeReUsed() || !canReUseActivity()) { 62 launchActivity(getActivityIntent()); 63 sTestActivity = getActivity(); 64 sTestActivity.setAllowFinish(!canReUseActivity()); 65 if (!canReUseActivity()) { 66 sTestActivity = null; 67 } 68 } else { 69 sTestActivity.resetContent(); 70 } 71 mBase.evaluate(); 72 } finally { 73 afterActivityFinished(); 74 } 75 } 76 } 77 } 78