Mocking static methods with Mockito

后端 未结 15 1094
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?
    0 讨论(0)
  • 2020-11-21 07:43

    Observation : When you call static method within a static entity, you need to change the class in @PrepareForTest.

    For e.g. :

    securityAlgo = MessageDigest.getInstance(SECURITY_ALGORITHM);
    

    For the above code if you need to mock MessageDigest class, use

    @PrepareForTest(MessageDigest.class)
    

    While if you have something like below :

    public class CustomObjectRule {
    
        object = DatatypeConverter.printHexBinary(MessageDigest.getInstance(SECURITY_ALGORITHM)
                 .digest(message.getBytes(ENCODING)));
    
    }
    

    then, you'd need to prepare the class this code resides in.

    @PrepareForTest(CustomObjectRule.class)
    

    And then mock the method :

    PowerMockito.mockStatic(MessageDigest.class);
    PowerMockito.when(MessageDigest.getInstance(Mockito.anyString()))
          .thenThrow(new RuntimeException());
    
    0 讨论(0)
  • 2020-11-21 07:44

    As mentioned before you can not mock static methods with mockito.

    If changing your testing framework is not an option you can do the following:

    Create an interface for DriverManager, mock this interface, inject it via some kind of dependency injection and verify on that mock.

    0 讨论(0)
提交回复
热议问题