How to write Junit for Interface default methods

后端 未结 5 1970
梦如初夏
梦如初夏 2021-02-05 15:24

Please help in writing Junit for the interface default method.

public interface ABC {
    default List getSrc(DEF def, XYZ xyz) t         


        
5条回答
  •  太阳男子
    2021-02-05 16:00

    As suggested in the answer, create implementation class for the interface and test it, for an example I modified getSrc method in your ABC interface, as below:

    import java.util.ArrayList;
    import java.util.List;
    
    public interface ABC {
    
        default List getSrc(DEF def, XYZ xyz) {
            final List defaultList = new ArrayList<>();
            defaultList.add("default");
            defaultList.add("another-default");
            return defaultList;
        }
    }
    

    Created an implementation class for the same, optionally you can create another method calling super method and write @Test for both, as I does:

    import java.util.List;
    
    public class ABCImpl implements ABC {
    
        public List getSrcImpl(DEF def, XYZ xyz) {
            final List list = getSrc(def, xyz);
            list.add("implementation");
            return list;
        }
    }
    

    Corresponding Test class for the implementation is as follows:

    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.empty;
    import static org.hamcrest.Matchers.is;
    import static org.hamcrest.Matchers.not;
    import static org.hamcrest.Matchers.contains;
    import java.util.Collection;
    import java.util.List;
    
    import org.junit.Before;
    import org.junit.Test;
    
    public class ABCImplTest {
    
        private ABCImpl abcImpl;
    
        @Before
        public void setup() {
            abcImpl = new ABCImpl();
        }
    
        @Test
        public void testGetSrc() throws Exception {
            List result = abcImpl.getSrc(new DEF(), new XYZ());
            assertThat((Collection) result, is(not(empty())));
            assertThat(result, contains("default", "another-default"));
        }
    
    
        @Test
        public void testABCImplGetSrc() throws Exception {
            List result = abcImpl.getSrcImpl(new DEF(), new XYZ());
            assertThat((Collection) result, is(not(empty())));
            assertThat(result, contains("default", "another-default", "implementation"));
        }
    }
    

提交回复
热议问题