Mockito-Android Test return method

Asked

Viewed 422 times

1

I’m trying to test a return of a method from my class on 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 my class, I did this way:

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

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

  • try Mockito.when(var.loadTexture("back.png")). thenCallRealMethod() and speak if something happens.

  • The test passes successfully regardless of the value I pass on loadTexture("blablabla");

1 answer

2


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

Mocks should be used to represent external objects that are necessary for the execution of class methods. 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, you notice that class A has a dependency on class B, so if you wanted to test class A, you would have to create a Mock of class B and explain what values it returns, that is, you would say the behavior of class B and then you would check if the class A acts correctly as it receives the data from 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 that case, you’re saying that when the method fazOutraCoisa() of B is called, it must return 10 to the one who called it ( class A). Therefore when using the assertEquals you want to know if class A is actually getting the return value of the method fazOutraCoisa of B.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.