How to write Junit for Interface default methods

后端 未结 5 1957
梦如初夏
梦如初夏 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 15:53

    I think there is a simpler way. It consists in implementing the interface with methods to be tested in the test class and invoking methods of default type directly. If necessary, the objects that are called internally are mocked. The previous example would be such that:

    Interface)

    public interface ABC {
        default List getSrc(DEF def, XYZ xyz) throws Exception {
          list() result=new Arraylist();
          result.add(def.toString());
          result.add(xyz.toString());
          return result;
        }
    }
    

    Test class)

    ...        
    @RunWith(MockitoJUnitRunner.class)
    public class ABCTest implements ABC{
    
        @Test
        public void testGetSrc() {
    
            list() result=getSrc(new DEF("Hi!"),new XYZ("bye!"));
    
            int actual=result.size();
            int expected=2;
            assertEquals(expected, actual);
    
        }
    

    If you need to test the launch of an exception, it will be enough to force its release from wrong parameters and correctly configure the test:

    ...        
    @Test(expected = GenericRuntimeException.class)
    public void test....
    ...
    

    I've checked it with a similar code and it works. It is also collected correctly in the coverage analysis.

提交回复
热议问题