How to test abstract class in Java with JUnit?

后端 未结 10 1238
野趣味
野趣味 2020-11-27 04:46

I am new to Java testing with JUnit. I have to work with Java and I would like to use unit tests.

My problem is: I have an abstract class with some abstract methods.

10条回答
  •  青春惊慌失措
    2020-11-27 04:57

    You could do something like this

    public abstract MyAbstractClass {
    
        @Autowire
        private MyMock myMock;        
    
        protected String sayHello() {
                return myMock.getHello() + ", " + getName();
        }
    
        public abstract String getName();
    }
    
    // this is your JUnit test
    public class MyAbstractClassTest extends MyAbstractClass {
    
        @Mock
        private MyMock myMock;
    
        @InjectMocks
        private MyAbstractClass thiz = this;
    
        private String myName = null;
    
        @Override
        public String getName() {
            return myName;
        }
    
        @Test
        public void testSayHello() {
            myName = "Johnny"
            when(myMock.getHello()).thenReturn("Hello");
            String result = sayHello();
            assertEquals("Hello, Johnny", result);
        }
    }
    

提交回复
热议问题