How to correctly mock ViewModel on androidTest

后端 未结 4 2109
野性不改
野性不改 2021-02-13 03:21

I\'m currently writing some UI unit tests for a fragment, and one of these @Test is to see if a list of objects is correctly displayed, this is not an integ

4条回答
  •  醉话见心
    2021-02-13 03:49

    In the example you provided, you are using mockito to return a mock for a specific instance of your view model, and not for every instance.

    In order to make this work, you will have to have your fragment use the exact view model mock that you have created.

    Most likely this would come from a store or a repository, so you could put your mock there? It really depends on how you setup the acquisition of the view model in your Fragments logic.

    Recommendations: 1) Mock the data sources the view model is constructed from or 2) add a fragment.setViewModel() and Mark it as only for use in tests. This is a little ugly, but if you don't want to mock data sources, it is pretty easy this way.

提交回复
热议问题