Error mocking Class which hold reference to SQLiteOpenHelper

前端 未结 3 561
傲寒
傲寒 2021-01-22 23:52

I write unit test for my Presenter, which is need to mock my Local Data Source.

Here is my simple test :

public class AddressPresenterTest {
           


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-23 00:34

    ✔ Answer

    After a couple hour i looking for solution, i get the simplest solution. I think there is some incomplete in android library for testing. So i just run this gradle command to cleanup :

    ./gradlew clean test
    

    And it works now, i just mock StaticDatabaseHelper class in this case. So this is my final testing Class :

    public class AddressPresenterTest {
    
        @Mock
        private AddressView mView;
    
        @Mock
        private AddressDataSource mDataSource;
    
        @Mock
        private AddressLocalDataSource mLocalDataSource;
    
        @Captor
        ArgumentCaptor> mProvinceCallbackCaptor;
    
        private AddressPresenter mPresenter;
    
        @Before
        public void beforeTest() throws Exception {
            MockitoAnnotations.initMocks(this);
    
            mPresenter = new AddressPresenter(mDataSource, mView);
            mPresenter.setLocalDataSource(mLocalDataSource);
        }
    
        @Test
        public void When_SelectProvince_DataIsNull_ShowErrorMessage() {
            mPresenter.getLocalProvinceById(2129023);
    
            // Cause data source has callback, we need to capture the callback
            ArgumentCaptor provinceIdCaptor = ArgumentCaptor.forClass(Integer.class);
            verify(mLocalDataSource).fetchProvinceById(provinceIdCaptor.capture(), mProvinceCallbackCaptor.capture());
            mProvinceCallbackCaptor.getValue().onFailedLoad();
    
            verify(mView).loadContentError();
        }
    }
    

    Hope this help, thank you

提交回复
热议问题