Mocking static methods with Mockito

后端 未结 15 1111
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:42

    Mocking of static methods in Mockito is possible since Mockito 3.4.0. For more details see:

    https://github.com/mockito/mockito/tree/v3.4.0

    https://github.com/mockito/mockito/issues/1013.

    In your case, something like this:

      @Test
      public void testStaticMockWithVerification() throws SQLException {
        try (MockedStatic dummy = Mockito.mockStatic(DriverManager.class)) {
          DatabaseConnectionFactory factory = new MySQLDatabaseConnectionFactory();
          dummy.when(() -> DriverManager.getConnection("arg1", "arg2", "arg3"))
            .thenReturn(new Connection() {/*...*/});
    
          factory.getConnection();
    
          dummy.verify(() -> DriverManager.getConnection(eq("arg1"), eq("arg2"), eq("arg3")));
        }
      }
    

    NOTE: this feature requires mockito-inline dependency.

提交回复
热议问题