4

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.

Progman
  • 16,827
  • 6
  • 33
  • 48
Shakakhan
  • 41
  • 1
  • 1
  • 2
  • 1
    you can make your private method package-private and test both of them separately, or refactor your code by making getMap static method or static function. – Dmitrii B Mar 28 '22 at 19:48
  • The class uses code that I didn’t create and can’t edit. – Shakakhan Mar 28 '22 at 19:51
  • 1
    If you're not allowed to change the code that you're testing, what will you do if your test fails? – Dawood ibn Kareem Mar 28 '22 at 20:35
  • 2
    Also, keep in mind that if you stub a private method, you're changing the behaviour of the system under test, which means that your tests are invalid. There's a reason why Mockito doesn't let you do this. – Dawood ibn Kareem Mar 28 '22 at 21:16
  • Ideally, you should never try to mock the private methods. You can modify your input parameters to public method and accordingly test out different conditions, considering the fact how the private method would behave for different input parameters passed on from your public method to private method. – Sandeep Lakdawala Mar 30 '22 at 06:29

2 Answers2

1

You should be able to mock it using powermock

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

mh377
  • 1,656
  • 5
  • 22
  • 41
-1

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