Search code examples
javamockingmockitojunit4

I want to use spy to mock a method but i need to get some dummy data in return


I want to mock the getUserDataFromExt() and pass the local hashmap and expecting it to return some list of data and also add/assign some values to the passed in hashmap.

Note: I cannot inject that hashmap from constructor and mock it.

 public List<Report> getUserData() {
    .............
    ..............
    Map<String, Set<Integer>> studyToRelationshipPk = new HashMap<>();
                List<NetworkUserSiteDetail> uniqueList = getUserDataFromExt(studyToRelationshipPk);

    ..............
    }

Is there a way that i can mock the method and still get the data from passed in local argument and return some list.


Solution

  • If you can't refactor your code, you will need to create a spy for your class (to mock for getUserDataFromExt).

    Then you can use thenAnswer to modify your HashMap and return the list:

    when(spy.getUserDataFromExt()).thenAnswer(
        new Answer() {
             public Object answer(InvocationOnMock invocation) {
    
                 // get your method arguments
                 Object[] args = invocation.getArguments();
    
                 // do whatever with your hashmap
    
                 // return your list
                 return ...
             }
        }
    );
    

    If you can refactor your code, it would probably be better to move the method getUserDataFromExt to a different method and mock it. You could still use the same way to modify both the parameter and the result.

    You'll also might want to consider changing the behaviour of the method - as modifying the parameter and return a result - can be quite unexpected from the view of others developers.