CodeNewbie Community 🌱

Tristan
Tristan

Posted on

Testing in Android. Better return value.

Introduction

  • Now that I have officially released my first app, which can be found HERE on the Google Play store. I want to add more features to my app, however, I think the next best step is to add some tests. So, this series is going to be a practical series dedicated to understanding testing in the Android framework.

Source code

  • You can find my source code HERE

Better return value

  • So inside the best practices section of the Android architecture guide it recommends adding a Resource class to wrap around our return values to encapsulate both the returned data and its state. Which is great, however, the the only problem is that the example is in Kotlin. So here is my example of converting the class displayed HERE into a Java class
public class Resource<T>{
    private  T data;
    private  String message;

    public Resource( T data, @Nullable String message){
        this.data = data;
        this.message = message;
    }

    public static <T> Resource<T> success( T data){
        return new Resource<>(data,null);
    }

    public static <T> Resource<T> loading(T data){
        return new Resource<>(data,null);
    }

    public static <T> Resource<T> error(T data, String message){
        return new Resource<>(data,message);
    }


    //GETTERS
    public T getData(){
        return this.data;
    }
    public String getMessage(){
        return this.message;
    }

}
Enter fullscreen mode Exit fullscreen mode
  • The code above is a pretty straight forward class. The only thing that might seem a little off is all the T which are called type parameters and allows us to use this class with multiple data types.

  • The main benefit of this class is to wrap the return values from the DAO in this Resource class. This allows us to provide our UI with more info. Especially when an error occurs.

  • This code might not seem relevant now but I will be using it to unit test the repository layer of my app.

Conclusion

  • Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.

Top comments (0)