Refactor BookmarkLocationsFragment to load favorites only when view is not null

* BookmarkLocationsFragment: load favorites locations only when view is not null.
* BookmarkLocationsFragmentTest: added spy and verify to test onResume() call initList() method.
This commit is contained in:
Saifuddin 2025-01-20 16:13:47 +05:30
parent edd52debfb
commit 9c352b4ba2
2 changed files with 17 additions and 11 deletions

View file

@ -1,6 +1,7 @@
package fr.free.nrw.commons.bookmarks.locations
import android.Manifest.permission
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
@ -8,7 +9,9 @@ import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.android.support.DaggerFragment
import fr.free.nrw.commons.R
@ -131,11 +134,13 @@ class BookmarkLocationsFragment : DaggerFragment() {
fun initList() {
var places: List<Place>
if(view != null) {
viewLifecycleOwner.lifecycleScope.launch {
places = controller.loadFavoritesLocations()
updateUIList(places)
}
}
}
private fun updateUIList(places: List<Place>) {
adapter.items = places

View file

@ -23,12 +23,14 @@ import fr.free.nrw.commons.nearby.Place
import fr.free.nrw.commons.nearby.fragments.CommonPlaceClickActions
import fr.free.nrw.commons.nearby.fragments.PlaceAdapter
import fr.free.nrw.commons.profile.ProfileActivity
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.spy
import org.mockito.MockitoAnnotations
import org.powermock.reflect.Whitebox
import org.robolectric.Robolectric
@ -133,12 +135,12 @@ class BookmarkLocationFragmentUnitTests {
fun testInitNonEmpty() {
runBlocking {
whenever(controller.loadFavoritesLocations()).thenReturn(mockBookmarkList)
}
val method: Method =
BookmarkLocationsFragment::class.java.getDeclaredMethod("initList")
method.isAccessible = true
method.invoke(fragment)
}
}
/**
* test onCreateView
@ -173,11 +175,10 @@ class BookmarkLocationFragmentUnitTests {
@Test
@Throws(Exception::class)
fun testOnResume() = runBlocking {
val fragmentSpy = spy(fragment)
whenever(controller.loadFavoritesLocations()).thenReturn(mockBookmarkList)
fragment.onResume()
verify(fragment).initList()
verify(adapter).items = mockBookmarkList
fragmentSpy.onResume()
verify(fragmentSpy).initList()
}
}