samedi 28 mai 2016

Unit test Android View

I am attempting to write some unit tests (that run on the JVM, not on an emulator or device) for an existing class and am running into some issues with how I should structure the tests or perhaps if what I'm wanting to do is even possible.

I have a class that gets a View injected into it, does some calculations and sets some values on View. Here's a concrete example:

public class Translate {

    public void doTranslate(View view, int x, int y) {
        int left = view.getLeft();
        int top = view.getTop();
        int width = view.getWidth();
        int height = view.getHeight();

        int deltaX = 2 * x;
        int deltaY = 3 * y;

        view.setLeft(left + deltaX);
        view.setTop(top + deltaY);
        view.setRight(left + deltaX + width);
        view.setBottom(top + deltaY + height);
    }
}

What I would like to accomplish with my unit tests is to determine:

  1. Did the deltaX and deltaY calculations get performed correctly?
  2. Did View get the calculated values set on it?

The way I thought I could solve this is to create a Mock View using Mockito and pass that in. My idea was that I'd set some initial values on the mock View, use the doTranslate() method to alter those values and then verify that the mock View had the new, correct values applied to it after being passed to the method. What I found instead was that mocks can't have their values changed. You can set them up to return whatever value you want, but it's not like you can set values on them dynamically like you can a real object.

Is my thinking about mocks correct or am I missing something?

One way I can think of solving this would require eliminating passing View in altogether and instead breaking the problem down into smaller methods. So I could create int calculateDeltaX(int x) and int calculateDeltaY(int y) methods and have them actually return values instead of modifying a View object. This would make the translate class easy to unit test, however I'd still have an issue in the calling class where I needed to verify, using tests, that calculateDeltaX() was called and its value set on View. Is there a good way to accomplish what I'm describing of breaking the problem down into small unit tests and verifying behavior of the calling class?

Aucun commentaire:

Enregistrer un commentaire