Mocking static methods with Mockito

后端 未结 15 1088
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:28

    Use JMockit framework. It worked for me. You don't have to write statements for mocking DBConenction.getConnection() method. Just the below code is enough.

    @Mock below is mockit.Mock package

    Connection jdbcConnection = Mockito.mock(Connection.class);
    
    MockUp mockUp = new MockUp() {
    
                DBConnection singleton = new DBConnection();
    
                @Mock
                public DBConnection getInstance() { 
                    return singleton;
                }
    
                @Mock
                public Connection getConnection() {
                    return jdbcConnection;
                }
             };
    

提交回复
热议问题