lundi 15 janvier 2018

How to test an Android class that depends on CountDownTimer

I'm writing a ViewModel for an android app, and it should implement and start a CountDownTimer in order to update some UI every now and then.

I started to practice TDD lately and I wonder what architecture decisions should I make in order to make the ViewModel testable (I want the test to run rapidly without depending on real timing mechanisms). I can't provide the CountDownTimer as a dependency because it's an abstract class that is implemented in the ViewModel itself, so I 'don't know' what implementation to give.

Generally speaking, what are the best practices for writing tests when working with frameworks that hold heavy constraints and with non-testable framework-code?

This is the code that I currently have. How do you make it testable?

import android.arch.lifecycle.ViewModel;
import android.os.CountDownTimer;

class MyViewModel extends ViewModel {

    private MyView myView;

    public void init(MyView myView) {
        this.myView = myView;
        new CountDownTimer(0, 1000) {
            @Override
            public void onTick(long l) {
                myView.updateUi(l);
            }

            @Override
            public void onFinish() {
                myView.updateUiFinished();
            }
        }.start();
    }

    public interface MyView {
        void updateUi(long l);

        void updateUiFinished();
    }
}

Aucun commentaire:

Enregistrer un commentaire