【问题标题】:Unit Test with Live Data always get error "Method getMainLooper in android.os.Looper not mocked."使用实时数据进行单元测试总是出错“android.os.Looper 中的方法 getMainLooper 未模拟。”
【发布时间】:2022-08-15 11:42:50
【问题描述】:

在我的 ViewModel 中,我使用实时数据来保存响应状态。这里的代码:

@HiltViewModel
class MainViewModel @Inject constructor(private val repository: Repository): ViewModel() {

    private val _charData = MutableLiveData<Response<List<Character>>>()

    val charData: LiveData<Response<List<Character>>>
        get() = _charData

    init {
        getCharacters()
    }

    fun getCharacters(){
        viewModelScope.launch {
            _charData.value = repository.getCharacters()
        }
    }
}

我的测试总是因该错误而失败,问题出在_charData.value = repository.getCharacters() 行中。我也看过同样的问题,应该通过添加@get:Rule val instantExecutorRule: InstantTaskExecutorRule = InstantTaskExecutorRule()来处理。但是,错误仍然存​​在。这是我的测试代码:

@RunWith(JUnit4::class)
class MainViewModelTest {
    @get:Rule
    val mainRule =  MainCoroutineRule()

    lateinit var repository: Repository

    lateinit var viewModel: MainViewModel

    @get:Rule
    val instantExecutorRule: InstantTaskExecutorRule = InstantTaskExecutorRule()

    @Before
    fun setUp(){
        MockitoAnnotations.openMocks(this)
        repository = MockRepository()
        viewModel = MainViewModel(repository)
    }

    @Test
    fun getCharactersSuccess() = runTest {
        val observer = mock<Observer<Response<List<Character>>>>()
        viewModel.getCharacters()
        viewModel.charData.observeForever(observer)
        assertTrue(viewModel.charData.value is Response.Success)
    }
}

我应该如何解决这个错误? 谢谢

    标签: android unit-testing android-livedata


    【解决方案1】:

    添加

    testOptions {
                unitTests.returnDefaultValues = true
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 2014-08-19
      相关资源
      最近更新 更多