Mocking static methods with Mockito

后端 未结 15 1112
Happy的楠姐
Happy的楠姐 2020-11-21 06:51

I\'ve written a factory to produce java.sql.Connection objects:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory         


        
15条回答
  •  遇见更好的自我
    2020-11-21 07:43

    Use PowerMockito on top of Mockito.

    Example code:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(DriverManager.class)
    public class Mocker {
    
        @Test
        public void shouldVerifyParameters() throws Exception {
    
            //given
            PowerMockito.mockStatic(DriverManager.class);
            BDDMockito.given(DriverManager.getConnection(...)).willReturn(...);
    
            //when
            sut.execute(); // System Under Test (sut)
    
            //then
            PowerMockito.verifyStatic();
            DriverManager.getConnection(...);
    
        }
    

    More information:

    • Why doesn't Mockito mock static methods?

提交回复
热议问题