Pablo Gonzalez
Pablo Gonzalez

Reputation: 1810

Instance variable stays null when using Mockito

I have the following class

package pckt.theclass;

public class TheClass {

    public String name = "testing";

    public void setTheName(){
        this.name = getNamesFromDB();
    }

    public String getNamesFromDB(){
        return "pablo";
    }

}

And this is the test class for it

package pckt.theclass;

import org.junit.*;
import org.mockito.Mockito;


public class TheClassTest {

    @Test
    public void testSetTheName() {

        //TheClass tc = Mockito.mock(TheClass.class);
        //Mockito.when(tc.getNamesFromDB()).thenReturn("dbName");
        TheClass tc = new TheClass();
        tc.setTheName();
        System.out.println("Name: "+tc.name);
        Assert.assertEquals("pablo", tc.name);
    }
}

If I run the test class as it is, it passes. However, if I uncomment the Mockito lines and modify assertEquals to expect "dbName" the test fails with the error

expectend "dbName" but was <null>

The issue is because the instance variable "name" is not being populated for some reason, even if it already has a value on its declaration. i'm new to Mockito so I'm not sure if I need to do something for this to work.

Thoughts?

Upvotes: 0

Views: 2517

Answers (1)

kryger
kryger

Reputation: 13181

This is because if you declare TheClass tc instance to be a mock, setTheName's body is no longer the one you defined in TheClass, but a stub method that returns null. This is because you didn't "train" setTheName to have any behaviour.

Effectively the mocked instance looks as if it was declared like this:

public class TheClass {
    public String name = null;

    public void setTheName(){
        // do nothing
    }

    public String getNamesFromDB(){
        return "dbName";
    }
}

You're making one of the basic Mockito mistakes: you're mocking the system under test.

Upvotes: 1

Related Questions