Skip to content
Fix Code Error

Mocking static methods with Mockito

March 13, 2021 by Code Error
Posted By: Anonymous

I’ve written a factory to produce java.sql.Connection objects:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {

    @Override public Connection getConnection() {
        try {
            return DriverManager.getConnection(...);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

I’d like to validate the parameters passed to DriverManager.getConnection, but I don’t know how to mock a static method. I’m using JUnit 4 and Mockito for my test cases. Is there a good way to mock/verify this specific use-case?

Solution

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?
Answered By: Anonymous

Related Articles

  • When I'm testing a web app by JUnit and Mockito I get many…
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • How do Mockito matchers work?
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2 has…
  • How to parse JSON file with Spring
  • ClassNotFoundException thrown
  • UnsatisfiedDependencyException: Error creating bean with…
  • Java verify void method calls n times with Mockito
  • Unable to run Robolectric and Espresso with a…
  • SQLException: No suitable Driver Found for…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to get current date in jquery?

Next Post:

‘npm’ is not recognized as internal or external command, operable program or batch file

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error