How to write junit tests for interfaces?

后端 未结 6 1775
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 03:49

What is the best way to write junit tests for interfaces so they can be used for the concrete implementing classes?

e.g. You have this interface and implementing cla

6条回答
  •  温柔的废话
    2020-11-28 04:11

    with java 8 i do this

    public interface MyInterfaceTest {
       public MyInterface createInstance();
    
       @Test
       default void testMyMethod_True() {
           MyInterface instance = createInstance();
           assertTrue(instance.myMethod(true));
       }
    
       @Test
       default void testMyMethod_False() {
           MyInterface instance = createInstance();
           assertFalse(instance.myMethod(false));
       }
    }
    
    public class MyClass1Test implements MyInterfaceTest {
        public MyInterface createInstance() {
            return new MyClass1();
        }
    }
    
    public class MyClass2Test implements MyInterfaceTest {
       public MyInterface createInstance() {
           return new MyClass2();
       }
    
       @Disabled
       @Override
       @Test
       public void testMyMethod_True() {
           MyInterfaceTest.super.testMyMethod_True();
       };
    }
    

提交回复
热议问题