How to mock a return from a call to a private method

17.1k Views Asked by At

I have a class which has a method I want to test, but it calls a private method in the same class to get a Map value. I want to mock what the private method returns to the method I want to test.

import java.util.*;

public class ClassOne {

    public List<String> getList(String exampleString) {
        List<String> exampleList = null;
        Map<String, String> exampleMap = getMap();
        String exampleValue = exampleMap.get(exampleString);
        // Does some stuff
        
        exampleList = Arrays.asList(exampleValue.split(","));
        return exampleList;
    }
    
    private Map<String, String> getMap(){
        Map<String, String> exampleMap = new HashMap<>();
        exampleMap.put("pre-defined String", "pre-defined String");
        return exampleMap;
    }

}

From what I can find- it seems like I want to use PowerMock, but I can't seem to figure it out.

A way to mock the return of the private method getMap() when it is called by the method getList.

2

There are 2 best solutions below

0
On

You should be able to mock it using powermock

"Mocking of Private Methods Using PowerMock | Baeldung" https://www.baeldung.com/powermock-private-method

4.1. Method With No Arguments but With Return Value

As a simple example, let’s mock the behavior of a private method with no arguments and force it to return the desired value:

LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());

when(mock, "getDefaultLuckyNumber").thenReturn(300);

In this case, we mock the private method getDefaultLuckyNumber and make it return a value of 300.

0
On

You will be able to return a call from private method provided its in the same class where the private method is