'Junit Mock a default method in an interface

I have a class called Class that it use another class Mapping, that implements an interface IMap with default class.

public interface IMap<K,V> {
  K fromSource(V source);

  default List<K> fromSourceList(List<V> sourceList) {
        List<K> result= new ArrayList<>();
        for (V source: sourceList) {
            result.add(this.fromSource(source));
        }
        return result;
  }
}

I try to unit test, with Mockito, my Class that call directly fromSourceList but, I can't stub default method.

I try with Mapping.java as Spy or Mock

  • Mockito.doReturn(objStubbed).when(mapping).fromSourceList();
  • Mockito.when(mapping.fromSourceList(anyList())).thenReturn(objStubbed);

Can you help me?


Another input: I need to test Class that use default interface like like this:

public class Mapping implements IMap<String,String> {
    
    @Override
    public String fromSource(String source) {
        return source.append(".");
    }
    
}

public class Class {
    
    private final Mapping mapping = new Mapping();
    
    public String doSomething(String string) {
        List<String> listStr = new ArrayList<>();
        listStr.add(string);
        listStr.add("This is a test");
        
        List<String> manipulatedString = mapping.fromSourceList(listStr);
        return manipulatedString.toString();
    }

}

@RunWith(MockitoJUnitRunner.class)
public class ClassTest {

    @Mock
    IMap<String, String> map;
    
    @InjectMock
    ClassTest class;

    @Test
    public void testMapMock(){
        List<String> target = new ArrayList<>();
        target.add("test.");
        target.add("This is a test.");

        when(map.fromSourceList(any())).thenReturn(target);
        
        String result = class.doSomething("test");

        Assert.assertEquals("test.This is a test.", result);
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source