Mocking static methods with Mockito

后端 未结 15 1095
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:26

    As mention @leokom, since Mockito 3.4.0 you can use the Mockito.mockStatic function to create mocks for static methods. Note that there are patches for this functionality in versions v3.4.2 and v3.4.6, Consider the use of a newer version.

    In your case could be 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")));
        }
      }
    

提交回复
热议问题