Mocking static methods with Mockito

后端 未结 15 1091
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:35

    For those who use JUnit 5, Powermock is not an option. You'll require the following dependencies to successfully mock a static method with just Mockito.

    testCompile    group: 'org.mockito', name: 'mockito-core',           version: '3.6.0'
    testCompile    group: 'org.mockito', name: 'mockito-junit-jupiter',  version: '3.6.0'
    testCompile    group: 'org.mockito', name: 'mockito-inline',         version: '3.6.0'
    

    mockito-junit-jupiter add supports for JUnit 5.

    And support for mocking static methods is provided by mockito-inline dependency.

    Example:

    @Test
    void returnUtilTest() {
        assertEquals("foo", UtilClass.staticMethod("foo"));
    
        try (MockedStatic classMock = mockStatic(UtilClass.class)) {
    
            classMock.when(() -> UtilClass.staticMethod("foo")).thenReturn("bar");
    
            assertEquals("bar", UtilClass.staticMethod("foo"));
         }
    
         assertEquals("foo", UtilClass.staticMethod("foo"));
    }
    

    The try-catch block is used to make the static mock remains temporary, so it's mocked only within that scope. But It's not mandatory to use a try-catch block.

提交回复
热议问题