Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Robolectric's Shadow Object and Mocking

I'm really new to Unit Testing on mobile. I want to write JUnit tests for Android mobile app. I came across Robolectric that is testing in IDE (for me, Eclipse)

But I really don't understand Shadow objects of Robolectric. Should I use them as mocking? What is the usage purpose of these Shadow objects like ShadowActivity, etc?

For example, I have Crashlytics, Google Analytics code in onCreate methods in almost every Activity class. Robolectric throws error when it come across with these lines. Could ShadowActivity solve these types of problems?

I'm sorry but, as I said I'm really new at Unit-Testing and Robolectric documentations are not helpful for a beginner.

like image 955
ersentekin Avatar asked Nov 15 '13 09:11

ersentekin


1 Answers

But I really don't understand Shadow objects of Robolectric. Should I use them as mocking? What is the usage purpose of these Shadow objects like ShadowActivity, etc?

Shadows are sort of like mocks or stubs, but not quite the same. Shadows exist to add additional methods that can be used in test to inspect the state of the underlying Android object. For example, many Android objects have setters for certain values, but no getters. We can add getters to the shadows and use them in test to assert on the underlying object.

For example, I have Crashlytics, Google Analytics code in onCreate methods in almost every Activity class. Robolectric throws error when it come across with these lines. Could ShadowActivity solve these types of problems?

Probably not. For this, you should be using dependency injection to inject a fake version of Crashlytics or GoogleAnalytics into your test.

The purpose of Robolectric is to fake out enough of the Android platform to allow you to run tests on your desktop JVM - not to emulate Android. Good engineering practices such as dependency injection or mocking can still be used.

I'm sorry but, as I said I'm really new at Unit-Testing and Robolectric documentations are not helpful for a beginner.

I agree. We're trying to make it better, but we have a long ways to go.

like image 60
Erich Douglass Avatar answered Sep 21 '22 01:09

Erich Douglass