Aaron Thompson
Aaron Thompson

Reputation: 1889

Robolectric: Shadows.shadowOf(Context) method not found

I have a custom system service that I am trying to mock and add to the shadow context in Robolectric 3.8.

I am trying to follow this answer: getSystemService in Robolectric returns object with null Context but it looks like shadowOf(android.content.Context) has been deprecated but I can find no mention of it in http://robolectric.org/migrating/

MyService myServiceMock = Mockito.mock(MyService.class);
Application application = (Application) ShadowApplication.getInstance().getApplicationContext();
ShadowContextImpl shadowContext = (ShadowContextImpl) Shadows.shadowOf(application.getBaseContext());
shadowContext.setSystemService(Context.MY_SERVICE, myServiceMock);

How do I mock/ shadow a system service in Robolectric 3.8?

Upvotes: 2

Views: 2890

Answers (1)

Michael Powell
Michael Powell

Reputation: 766

ShadowContextImpl shadowContext = Shadow.extract(RuntimeEnvironment.application.getBaseContext());
shadowContext.setSystemService(key, service);

Upvotes: 3

Related Questions