Stubbing doesn't work inside mockstatic block

Viewed 59

I'm writing a unit test. I have to stub instance's methods and static methods. For the static methods, I use mockStatic of Mockito. After I created mockStatic for Classes, other stubs don't work. The value I returned are being null. Could you please help me to resolve the issue?

public void assertGetConnection() throws SQLException {
    try (MockedStatic<PipelineDataSourceConfigurationFactory> mockedStatic = mockStatic(PipelineDataSourceConfigurationFactory.class, invocation -> {
        Method method = invocation.getMethod();
        if ("newInstance".equals(method.getName())) {
            return invocation.getMock();
        } else {
            return invocation.callRealMethod();
        }
    })) {
                 when(sourceYamlPipelineDataSourceConfiguration.getType()).thenReturn("JDBC"); // NOT WORKING ; ALWAYS It's NULL

        
        mockedStatic.when(() -> PipelineDataSourceConfigurationFactory.newInstance(anyString(), eq("source"))).thenReturn(sourceScalingDataSourceConfig);

        MySQLDataSourcePreparer mySQLDataSourcePreparer = new MySQLDataSourcePreparer();
        mySQLDataSourcePreparer.prepareTargetTables(prepareTargetTablesParameter);
        verify(sourceDataSource).getConnection();
        verify(targetDataSource).getConnection();
    }
   
}
0 Answers
Related