Mocking static methods with Mockito

后端 未结 15 1140
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

    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());
    

提交回复
热议问题