Easier Testing with Data Binding & BindingAdapters

Chris Michael
Kin + Carta Created

--

The data binding library has been around for quite some time, however not that many developers use it. One of the main reasons behind this lack of adoption is the belief that it results in untestable code. However, when used correctly it can actually make testing your code easier, while also adding to increased code reusability. In this article we will go through some examples to see how we can use data binding effectively to achieve this and what to avoid doing.

Separating View logic from Presentation logic

A common use case that we encounter on most projects is handling the visibility of a view. Typically someone would write some code like the following to handle this.

This approach results in code that is difficult to test and requires Robolectric or Espresso. The logic of the if condition though, data == null, is presentation logic and can be moved to the view model where it can easily be tested. After doing so the code looks like this.

However testing the remaining view logic is still not easy, as code remains in our Activity. With data binding though, this piece of code can be made reusable and easy to test. But first let’s have a look at how someone might use data binding inappropriately by using the expression language provided by the library in xml.

This code can not be unit tested nor can it be reused. The expression language has some specific use cases, however this is not one of them and should not be used in most cases. Instead, we should utilise another feature of data binding called Binding Adapters. By making use of them, the code will now look like this.

The view logic has now been moved to the BindingAdapters class and is now also reusable. It is also now much easier to test with Robolectric or a mocking library like MockK, as it is not tied to an Activity or Fragment lifecycle. The bindings in the xml can also be tested by creating some light weight, fast to run instrumentation tests.

Conclusion

As with every tool, in order for it to be effective it has to be used correctly. Following some simple rules when using data binding, your code can be easier to test and reuse, which also results in a code base that is easier to maintain.

--

--