Hello I have the following project structure
--App
|--SDK1
|--SDK2
In app I have some test for check SDK1 and SDK2.
In SDK I have a singleton pattern only to set the context by the application class that is in App.
And the context is set in the SDK1.singleton in the App.Application.onCreate
The problem is that when I try to execute the following code I always get null:
@RunWith(RobolectricTestRunner.class)
public class CallTest {
@Before
public void setUp() throws Exception {}
@Test
public void connectToSocketTest() {
if (BuildConfig.FLAVOR.equals("dev")) {
Context context = SDK1.getInstance().getContext();
assertNotNull(context);
...
Any idea why this happens, and how can solve it?
That's not the recommended way to get app context in Android using robolectric. You can get your activity by using below code...
Activity activity = Robolectric.setupActivity(MyActivity.class);
To get the app context, just call activity.getApplicationContext()
.
EDIT1: If you're using the latest Robolectric version, use
Robolectric.buildActivity(DashboardActivity.class)
instead.EDIT2: Make sure your
SDK1
extendsMultiDexApplication". Add this
@Config(manifest=Config.NONE, application = App.class, sdk = 17)` to the top of your test class.
Let me know if it works.