Mockito不模拟存储库

时间:2019-09-09 19:44:12

标签: android testing kotlin mockito viewmodel

我尝试用ViewModel测试我的mockito

这是我的TestClass:

@RunWith(JUnit4::class)
class RatesViewModelTest {

    @Rule @JvmField
    open val instantExecutorRule = InstantTaskExecutorRule()

    @Mock
    var observer: Observer<Pair<ArrayList<CurrencyExchangerModel>,Boolean>>? = null

    @Mock
    private lateinit var repository: RatesRepository

    private var currencyList = ArrayList<CurrencyModel>()

    private lateinit var viewModel : RatesViewModel

    @Before
    fun setUp(){
        MockitoAnnotations.initMocks(this)

        currencyList.add(CurrencyModel("BASE"))
        viewModel = RatesViewModel(repository!!)
        viewModel.getCurrencyExchangerObservableList().observeForever(observer!!)
    }

    @Test
    fun testNull(){
        Mockito.`when`(repository.getFlowableRates()).thenReturn( Flowable.just(currencyList) )
        assertTrue(viewModel.getCurrencyExchangerObservableList().hasObservers())

    }
}

调用此方法时:

Mockito.`when`(repository.getFlowableRates()).thenReturn( Flowable.just(currencyList) )

我收到此错误:

  

kotlin.UninitializedPropertyAccessException:lateinit属性数据库具有   尚未初始化

在此存储库:

open class RatesRepository(context:Context) : BaseRepository(context){

    @Inject
    lateinit var ratesAPI: RatesAPI

    @Inject
    lateinit var db: Database

    /**
     * load the updated chatList from API
     */
    fun loadCurrencyRatesFromAPI(): Single<ArrayList<CurrencyModel>> {
        val supportedCurrency = context.resources.getStringArray(R.array.currencies)
        return ratesAPI.getLatestRates(EUR_CURRENCY_ID).map { RatesConverter.getRatesListFromDTO(it,supportedCurrency) }
    }

    /**
     * save rates on DB
     */
    fun saveCurrencyRatesOnDB(list:ArrayList<CurrencyModel>): Completable {
        return db.currencyRatesDAO().insertAll(list)
    }

    /**
     * get flawable rates from DB
     */
    fun getFlowableRates(): Flowable<List<CurrencyModel>> {
        return db.currencyRatesDAO().getAll()
    }

    companion object {
        const val EUR_CURRENCY_ID = "EUR" //BASE
    }
}

我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

定义模拟的行为并使用when(...).then(...)的模拟符号时,
方法本身会被调用(通过模仿,通常与您的测试无关)。

在您的情况下,这是一个问题,因为db未初始化。

在这种情况下,为避免此问题,请使用doReturn(...).when(...)语法,
不会导致方法调用。

Mockito.doReturn(Flowable.just(currencyList)).when(repository).getFlowableRates();

(您可能需要调整此java语法以使其与kotlin兼容)