Mockito-Android Test method return

1

I am trying to test a return from a method of my class in an Android project. I'm doing it this way:

MyClass var = Mockito.mock(MyClass.class);

With this, I already have my instance. Now I need to test methods of this class, I did it this way:

Mockito.doCallRealMethod().when(var).loadTexture("back.png")

The return is always coming null. But the image exists and was not meant to be returning null ...

    
asked by anonymous 14.01.2015 / 21:50

1 answer

2

The problem is that you are trying to test a "Mockada" class, that is, you are not testing the actual class but rather a "default" instance of it. That's why when you give loadTexture() it is returned null .

Mocks should be used to represent external objects and are required to execute methods of a class. For example:

public class MinhaClasseA{

    private MinhaClasseB mcB;

    public MinhaClasseA(MinhaClasseB mcB){

        this.mcB = mcB
    }

    public int fazAlgumaCoisa(){

        return mcB.fazOutraCoisa();
    }
}

public class MinhaClasseB{

    public int fazOutraCoisa(){

        return 10;
    }
}

In this case, we realize that class A has a dependence on class B, so if you wanted to test class A, you would have to create a class B mock and explain what values it returns, ie you I would say the behavior of class B and then you would check if class A acts correctly as it receives the data of B.

Example:

MinhaClasseB mcBMock = Mockito.mock(MinhaClasseB.class);
MinhaClasseA mcA = new MinhaClasseA(mcBMock);

int intMock = 10;

when(mcBMock.fazOutraCoisa()).thenReturn(intMock);

assertEquals(mcA.fazAlgumaCoisa(),intMock);

In this case, you are saying that when the fazOutraCoisa() method of B is called, it should return 10 to the caller (the class A). So when using assertEquals you want to know if class A is actually getting the return value of the fazOutraCoisa method of B.

    
31.07.2015 / 06:29