Sathish G
Sathish G

Reputation: 153

How to perform Unit Test using Java Mockito

I'm trying test this code using mockito, so need to mock the result as error and test the code. In this case, I've hardcoded the result as 1.

public class RetrieveData {
    public int retrieveMetaData()  {
        int retries = 0;
        int result = 0;
        int MAX_RETRIES = 3;
        while (retries++ < MAX_RETRIES) {
            try {
                result = 1;
            } catch (Exception e) {
                if(retries < MAX_RETRIES) {
                    System.out.println(" retries  :" + retries );
                } else {
                    throw e;
                }
            }
        }
        return result;
    }
    public static void main(String[] args) {
        int result ;
        RetrieveData obj = new RetrieveData();
        result = obj.retrieveMetaData();
        System.out.println(result);
    }
}

Mockito:

import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class TestretrieveMetaData {

    @Test
    public void test_retrieveMetaData() throws Exception {
        RetrieveData resultObj = mock(RetrieveData.class);

        // how to add the mock for the result.

    }
}

Upvotes: 0

Views: 72

Answers (1)

GhostCat
GhostCat

Reputation: 140407

First of all, you have to understand what you intend to do!

You see, you either mock a class X ... because an instance of X is used in some class Y, and you intend to test Y. Or you intend to test class X, but then you shouldn't mock instances of X! Either you test X, or you use X for testing something else.

Assuming that you want to mock an instance of your class RetrieveData, you simply do:

RetrieveData resultObj = Mockito.mock(RetrieveData.class);
Mockito.when(resultObj.retrieveMetaData()).thenReturn(42);

So, to align with that comment by Tobb: you can't "mock" that result field alone. If at all, you can mock complete instances of your class. But as said: that only makes sense when you use that instance within another class you intend to test.

Long story short: as said, the real issue is that you are trying to use concepts that you simply do not understand (no judgement here). My recommendation: start by reading a good tutorial on Mockito. Then spent a lot of time thinking "how can I write code that I can test in reasonable ways". You are trying to start with step 10, but that won't work, because you can only do that when you made steps 1 to 9 before, and understand what they are about.

And yes, you can use a Mockito spy when you want to "partial mocking". Using that, you can test parts of X, whilst also "mocking out" other parts of X. But that is really an advanced feature, and most likely not the topic you should study first.

Upvotes: 3

Related Questions