java.util.NoSuchElementException: 流为空

java.util.NoSuchElementException: Flow is empty

我正在尝试使用 JUnit 4 的单元测试来测试此存储库

class AppRepository @Inject constructor(
    private val networkHelper: NetworkHelper,
    private val weatherMapper: WeatherMapper,
    private val cacheHelper: CacheHelper
) : Repository {
    override fun fetchWeatherInfo(lat: Double, lng: Double): Flow<AppResult<Weather>> {
        return networkHelper.getWeatherInfo(lat, lng).map {
            when(it){
                is AppResult.Error -> AppResult.Error(it.errorMessage)
                is AppResult.Success -> AppResult.Success(weatherMapper.map(it.data))
            }
        }
    }
}

所以我做了一个单元测试 class 像这样使用协程调度器并模拟一些接口 对于存储库

@ExperimentalCoroutinesApi
@RunWith(JUnit4::class)
class AppRepositoryTest{
    private val dispatcher = TestCoroutineDispatcher()
    @Mock
    private lateinit var networkHelper: NetworkHelper
    @Mock
    private lateinit var cacheHelper: CacheHelper
    private val mapper=WeatherMapper()
    private lateinit var repository: AppRepository
    @Before
    fun setup(){
        MockitoAnnotations.openMocks(this)
        repository= AppRepository(networkHelper,mapper,cacheHelper)
    }
    @Test
    fun`check if weather info returned failed`(){
       dispatcher.runBlockingTest {
           val expected:AppResult<Weather> = AppResult.Error("Can't load weather info")
           `when`(networkHelper.getWeatherInfo(1.0,1.0)).thenReturn(
               flow { AppResult.Error("Can't load weather info") }
           )
          val result= repository.fetchWeatherInfo(1.0,1.0).single()
          assertEquals(expected,result)
       }
    }
}

我想为当前的存储库功能测试一个失败的案例,但由于这个错误失败崩溃了

Flow is empty
java.util.NoSuchElementException: Flow is empty
    at kotlinx.coroutines.flow.FlowKt__ReduceKt.single(Reduce.kt:62)
    at kotlinx.coroutines.flow.FlowKt.single(Unknown Source)
    at com.isma3il.photoweatherapp.data.repositories.AppRepositoryTest$check if weather info returned failed.invokeSuspend(AppRepositoryTest.kt:73)
    at com.isma3il.photoweatherapp.data.repositories.AppRepositoryTest$check if weather info returned failed.invoke(AppRepositoryTest.kt)
    at com.isma3il.photoweatherapp.data.repositories.AppRepositoryTest$check if weather info returned failed.invoke(AppRepositoryTest.kt)

那么如何解决这个问题以及如何在测试中使用流程?

我完全忘记在流生成器中发出数据 像这样

`when`(networkHelper.getWeatherInfo(1.0,1.0)).thenReturn(
           flow { emit(AppResult.Error("Can't load weather info")) }
       )

这对我有用。