Android: Unit testing Android applications with Robolectric and Mockito

后端 未结 4 1538
没有蜡笔的小新
没有蜡笔的小新 2021-02-19 22:20

I have a Java library that uses a few things from the Android APIs. I\'d like to use Mockito to write unit tests for this library.

Is there a way I can go about this? <

4条回答
  •  無奈伤痛
    2021-02-19 23:12

    You can avoid it, for everything that has nothing to do with the Android SDK internal classes. That's what I'm doing for my Android projects (although I use JMock2, not Mockito).

    I have two test projects.

    • The first one uses JUnit4 and JMock2 that I added myself as dependencies. I test all the "business logic" classes, but I can't test anything that has to do with Android (UI classes, SQLiteOpenHelper, etc.) If I try to use them in my tests, I get the dreaded Stub! exception.

    • The second one to test the UI, using ActivityInstrumentationTestCase2 and Robotium.

    That may seem like a lot of work and complex, but really it's not, and I actually think it's better to separate them. UI tests are not "real" unit-tests and they often test some features across multiple units. If you properly separate your UI layer from your business logic (and doing this separation of tests will force you to do that, in TDD style), then it's all nice and smooth.

提交回复
热议问题