Home » Android » android – Get activity `ViewDataBinding` field inside `Robolectric` unit test after being assigned

android – Get activity `ViewDataBinding` field inside `Robolectric` unit test after being assigned

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am writing a Robolectric unit test which requires me to make use of the activity under test view data binding class(ViewDataBinding), unfortunately with no luck I am stuck with it being null inside of the unit test

inside of MainActiviy class:

...
ActivityMainBinding binding; // <-- this field returns null inside unit test
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
}
...

If anyone has written a test with a similar requirement please could you demonstrate an example of how you got the ViewDataBinding classed to be assigned before the test completed. Thanks!

Note: I am using Android Studio 2.2

How to&Answers:

I found out that testing with Robolectric version 3.1 was my issue and after upgrading to using Robolectric version 3.1.4 the activities ViewDataBinding field was no longer returning null

See PR: https://github.com/emartynov/android-architecture/pull/1

Thanks to @EugenMartynov for your contribution towards this issue.

Note: Used Gradle version 3.1 for building project, if you do decide to use Gradle version 3.1 and experience other issues after upgrading.Kindly look at Gradles change logs to update your Gradle build scripts(build.gradle) accordingly, before commenting other unrelated issues.