Mocking static methods with Mockito

后端 未结 15 1139
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:30

    I had a similar issue. The accepted answer did not work for me, until I made the change: @PrepareForTest(TheClassThatContainsStaticMethod.class), according to PowerMock's documentation for mockStatic.

    And I don't have to use BDDMockito.

    My class:

    public class SmokeRouteBuilder {
        public static String smokeMessageId() {
            try {
                return InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                log.error("Exception occurred while fetching localhost address", e);
                return UUID.randomUUID().toString();
            }
        }
    }
    

    My test class:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(SmokeRouteBuilder.class)
    public class SmokeRouteBuilderTest {
        @Test
        public void testSmokeMessageId_exception() throws UnknownHostException {
            UUID id = UUID.randomUUID();
    
            mockStatic(InetAddress.class);
            mockStatic(UUID.class);
            when(InetAddress.getLocalHost()).thenThrow(UnknownHostException.class);
            when(UUID.randomUUID()).thenReturn(id);
    
            assertEquals(id.toString(), SmokeRouteBuilder.smokeMessageId());
        }
    }
    

提交回复
热议问题