1 /* 2 * Copyright 2018 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 com.android.car.arch.common.testing; 18 19 import android.annotation.NonNull; 20 21 import androidx.annotation.RestrictTo; 22 import androidx.lifecycle.Lifecycle; 23 import androidx.lifecycle.LifecycleOwner; 24 import androidx.lifecycle.LifecycleRegistry; 25 26 import org.junit.rules.ExternalResource; 27 28 /** 29 * A LifecycleOwner whose {@link Lifecycle} is RESUMED during the test and DESTROYED after. The 30 * {@code Lifecycle} can be changed during the test using {@link #markState(Lifecycle.State)}. 31 */ 32 @RestrictTo(RestrictTo.Scope.TESTS) 33 public class TestLifecycleOwner extends ExternalResource implements LifecycleOwner { 34 35 private final LifecycleRegistry mRegistry = new LifecycleRegistry(this); 36 37 @NonNull 38 @Override getLifecycle()39 public Lifecycle getLifecycle() { 40 return mRegistry; 41 } 42 43 @Override before()44 protected void before() throws Throwable { 45 super.before(); 46 mRegistry.markState(Lifecycle.State.RESUMED); 47 } 48 49 @Override after()50 protected void after() { 51 mRegistry.markState(Lifecycle.State.DESTROYED); 52 super.after(); 53 } 54 55 /** 56 * Move the {@code Lifecycle} to the specified state. 57 * 58 * @see LifecycleRegistry#markState(Lifecycle.State) 59 */ markState(Lifecycle.State state)60 public void markState(Lifecycle.State state) { 61 mRegistry.markState(state); 62 } 63 } 64