blackpanther
blackpanther

Reputation: 11486

Unit testing with Mockito resets a mocked class' instance variable to null

I have mocked a Message class as follows (within a TestNG unit test class):

@BeforeMethod
protected void setUp() {
    message = mock(Message.class);
}

I can assure you that I have declared message of type Message in the Unit test class. Now, the Message class has an instance variable called category which is of type String as follows:

public class Message {
    private String category;

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
}

Okay, now the problem: within a small test method, I have to set the category of a mocked message instance and then use that category for another task in the unit test. However, after I set the category for the mocked message, it reverts to null again. This is the code:

public void shouldSendMessagesWithCategory() {
    message.setCategory("F1 Racing"); // SET THE CATEGORY

    raceResults.addSubscriber("F1 Racing", clientA); 
    System.out.println("Cat" + message.getCategory()); // THE MESSAGE's CATEGORY IS NULL

    raceResults.send(message);

    verify(clientA).receive(message);
}

The console prints out null - so I definitely know it's null. I've been trying to figure this out for two days, but it just seems I'm missing something. So any help would be greatly appreciated.

Upvotes: 1

Views: 2217

Answers (2)

BarrySW19
BarrySW19

Reputation: 3809

The "message" handle does not point to a real Message object - it points to a mock'ed object which has none of the functionality of the real thing. If you want the mock'ed object to return a value from getCategory() you will have to mock that too. Something like:

when(message.getCategory()).thenReturn("My Category");

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

You can use spy() instead of Mock(). Then you can keep the set value. You have another option. You can use doReturn("F1 Racing").when(message).getCategory(); to return the value you want to return.

Upvotes: 1

Related Questions