@@ -65,6 +65,7 @@ class FragmentKtTest {
65
65
)
66
66
67
67
val fragment: Fragment = mock()
68
+ doReturn(true ).`when `(fragment).isAdded
68
69
69
70
val view = View (testContext)
70
71
val activity = Robolectric .buildActivity(Activity ::class .java).create().get()
@@ -114,4 +115,68 @@ class FragmentKtTest {
114
115
assertFalse(latch.await(1 , TimeUnit .SECONDS ))
115
116
assertEquals(26 , receivedValue)
116
117
}
118
+
119
+ @Test
120
+ @Synchronized
121
+ @ExperimentalCoroutinesApi // consumeFrom
122
+ @ObsoleteCoroutinesApi // consumeFrom
123
+ fun `consumeFrom does not run when fragment is not added` () {
124
+ val owner = MockedLifecycleOwner (Lifecycle .State .STARTED )
125
+
126
+ val store = Store (
127
+ TestState (counter = 23 ),
128
+ ::reducer
129
+ )
130
+
131
+ val fragment: Fragment = mock()
132
+
133
+ val view = View (testContext)
134
+ val activity = Robolectric .buildActivity(Activity ::class .java).create().get()
135
+ activity.windowManager.addView(view, WindowManager .LayoutParams (100 , 100 ))
136
+ assertTrue(view.isAttachedToWindow)
137
+ doReturn(view).`when `(fragment).view
138
+ doReturn(owner.lifecycle).`when `(fragment).lifecycle
139
+
140
+ doReturn(true ).`when `(fragment).isAdded
141
+
142
+ var receivedValue = 0
143
+ var latch = CountDownLatch (1 )
144
+
145
+ fragment.consumeFrom(store) { state ->
146
+ receivedValue = state.counter
147
+ latch.countDown()
148
+ }
149
+
150
+ assertTrue(latch.await(1 , TimeUnit .SECONDS ))
151
+ assertEquals(23 , receivedValue)
152
+
153
+ latch = CountDownLatch (1 )
154
+ store.dispatch(TestAction .IncrementAction ).joinBlocking()
155
+ assertTrue(latch.await(1 , TimeUnit .SECONDS ))
156
+ assertEquals(24 , receivedValue)
157
+
158
+ latch = CountDownLatch (1 )
159
+ store.dispatch(TestAction .IncrementAction ).joinBlocking()
160
+ assertTrue(latch.await(1 , TimeUnit .SECONDS ))
161
+ assertEquals(25 , receivedValue)
162
+
163
+ doReturn(false ).`when `(fragment).isAdded
164
+
165
+ latch = CountDownLatch (1 )
166
+ store.dispatch(TestAction .IncrementAction ).joinBlocking()
167
+ assertFalse(latch.await(1 , TimeUnit .SECONDS ))
168
+ assertEquals(25 , receivedValue)
169
+
170
+ latch = CountDownLatch (1 )
171
+ store.dispatch(TestAction .IncrementAction ).joinBlocking()
172
+ assertFalse(latch.await(1 , TimeUnit .SECONDS ))
173
+ assertEquals(25 , receivedValue)
174
+
175
+ doReturn(true ).`when `(fragment).isAdded
176
+
177
+ latch = CountDownLatch (1 )
178
+ store.dispatch(TestAction .IncrementAction ).joinBlocking()
179
+ assertTrue(latch.await(1 , TimeUnit .SECONDS ))
180
+ assertEquals(28 , receivedValue)
181
+ }
117
182
}
0 commit comments