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
17package androidx.fragment.app;
18
19import static org.junit.Assert.assertEquals;
20
21import android.os.Bundle;
22import android.support.test.annotation.UiThreadTest;
23import android.support.test.filters.SmallTest;
24import android.support.test.rule.ActivityTestRule;
25import android.support.test.runner.AndroidJUnit4;
26
27import androidx.fragment.app.test.EmptyFragmentTestActivity;
28import androidx.lifecycle.Lifecycle;
29import androidx.lifecycle.LifecycleObserver;
30import androidx.lifecycle.OnLifecycleEvent;
31
32import org.junit.Assert;
33import org.junit.Rule;
34import org.junit.Test;
35import org.junit.runner.RunWith;
36
37@RunWith(AndroidJUnit4.class)
38@SmallTest
39public class FragmentArchLifecycleTest {
40
41    @Rule
42    public ActivityTestRule<EmptyFragmentTestActivity> mActivityRule =
43            new ActivityTestRule<>(EmptyFragmentTestActivity.class);
44
45    @Test
46    @UiThreadTest
47    public void testFragmentAdditionDuringOnStop() {
48        final EmptyFragmentTestActivity activity = mActivityRule.getActivity();
49        final FragmentManager fm = activity.getSupportFragmentManager();
50
51        final Fragment first = new Fragment();
52        final Fragment second = new Fragment();
53        fm.beginTransaction().add(first, "first").commitNow();
54        first.getLifecycle().addObserver(new LifecycleObserver() {
55            @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
56            public void onStop() {
57                fm.beginTransaction().add(second, "second").commitNow();
58                first.getLifecycle().removeObserver(this);
59            }
60        });
61        activity.onSaveInstanceState(new Bundle());
62        assertEquals(Lifecycle.State.CREATED, first.getLifecycle().getCurrentState());
63        assertEquals(Lifecycle.State.CREATED, second.getLifecycle().getCurrentState());
64        Assert.assertEquals(Lifecycle.State.CREATED, activity.getLifecycle().getCurrentState());
65    }
66}
67