Mock database driver

后端 未结 7 1357
臣服心动
臣服心动 2021-01-17 12:34

Is there some kind of JDBC driver which simply ignores database calls?

For the development I am migrating an application to a virtual machine. Here I want to work on

7条回答
  •  不思量自难忘°
    2021-01-17 13:10

    If you want to do unit tests, not an integration tests, than you can use a very basic and simple approach, using Mockito only, like this:

    public class JDBCLowLevelTest {
    
        private TestedClass tested;
        private Connection connection;
        private static Driver driver;
    
        @BeforeClass
        public static void setUpClass() throws Exception {
            // (Optional) Print DriverManager logs to system out
            DriverManager.setLogWriter(new PrintWriter((System.out)));
    
            // (Optional) Sometimes you need to get rid of a driver (e.g JDBC-ODBC Bridge)
            Driver configuredDriver = DriverManager.getDriver("jdbc:odbc:url");
    
            System.out.println("De-registering the configured driver: " + configuredDriver);
            DriverManager.deregisterDriver(configuredDriver);
    
            // Register the mocked driver
            driver = mock(Driver.class);
            System.out.println("Registering the mock driver: " + driver);
            DriverManager.registerDriver(driver);
        }
    
        @AfterClass
        public static void tearDown() throws Exception {
            // Let's cleanup the global state
            System.out.println("De-registering the mock driver: " + driver);
            DriverManager.deregisterDriver(driver);
        }
    
        @Before
        public void setUp() throws Exception {
            // given
            tested = new TestedClass();
    
            connection = mock(Connection.class);
    
            given(driver.acceptsURL(anyString())).willReturn(true);
            given(driver.connect(anyString(), Matchers.any()))
                    .willReturn(connection);
    
        }
    }
    

    Than you can test various scenarios, like in any other Mockito test e.g.

    @Test
    public void shouldHandleDoubleException() throws Exception {
        // given
        SomeData someData = new SomeData();
    
        given(connection.prepareCall(anyString()))
                .willThrow(new SQLException("Prepare call"));
        willThrow(new SQLException("Close exception")).given(connection).close();
    
        // when
        SomeResponse response = testClass.someMethod(someData);
    
        // then
        assertThat(response, is(SOME_ERROR));
    }
    

提交回复
热议问题