androidmockitorobolectricstubs

Difference between a stub, a mockito "mock" class, and a Robolectric "shadow" object


These are obviously related and have some similarities, but I am not sure what sets them apart. In the robolectric documentation, it is emphasized that Shadow Classes are not Mock or Stub classes. How are these different, and how would each be used?

Note: I think in this case, a practical example ("you would use a mock class to test such-and-such, which you could not test with a shadow class because of such-and-such") more than simply an overview would be especially useful and illustrative.


Solution

  • Think of a simple unit test for MyActivity class where you will not use Robolectric.setupActivity. You write a test case where you call MyActivity.onCreate to check that some preinitialisation is done when called. This test case will fail at super.onCreate call which is forced by android system.

    Mock will not help because you don't use a member variable which could be mocked.

    A Stub will not help because of the inheritance you can stub the onCreate method for you activity which makes testing pointless.

    You miss Spy but this will also not help because of the inheritance. With Spy can avoid the real onCreate call like stubbing but makes testing also pointless.

    The Shadow can help at this situation. This handles more like a proxy. There can be an explicit proxy for each inherited class. It can intercept each type of method call also for static methods. For you example we can create a proxy for the android.app.Activity which will shadow the onCreate method and instead of throwing exceptions it will do nothing... There you can save this event so you can later check that this super.method was called with expected arguments if necessary ;)