Mock database driver

后端 未结 7 1355
臣服心动
臣服心动 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:09

    jOOQ ships with a MockConnection that can be provided with a MockDataProvider, which is much easier to implement than the complete JDBC API. This blog post shows how to use the MockConnection: http://blog.jooq.org/2013/02/20/easy-mocking-of-your-database/

    An example:

    MockDataProvider provider = new MockDataProvider() {
    
        // Your contract is to return execution results, given a context
        // object, which contains SQL statement(s), bind values, and some
        // other context values
        @Override
        public MockResult[] execute(MockExecuteContext context) 
        throws SQLException {
    
            // Use ordinary jOOQ API to create an org.jooq.Result object.
            // You can also use ordinary jOOQ API to load CSV files or
            // other formats, here!
            DSLContext create = DSL.using(...);
            Result result = create.newResult(MY_TABLE);
            result.add(create.newRecord(MY_TABLE));
    
            // Now, return 1-many results, depending on whether this is
            // a batch/multi-result context
            return new MockResult[] {
                new MockResult(1, result)
            };
        }
    };
    
    // Put your provider into a MockConnection and use that connection
    // in your application. In this case, with a jOOQ DSLContext:
    Connection connection = new MockConnection(provider);
    DSLContext create = DSL.using(connection, dialect);
    
    // Done! just use regular jOOQ API. It will return the values
    // that you've specified in your MockDataProvider
    assertEquals(1, create.selectOne().fetch().size());
    

    There is also the MockFileDatabase, which helps you matching dummy results with SQL strings by writing a text file like this:

    # This is a sample test database for MockFileDatabase
    # Its syntax is inspired from H2's test script files
    
    # When this query is executed...
    select 'A' from dual;
    # ... then, return the following result
    > A
    > -
    > A
    @ rows: 1
    
    # Just list all possible query / result combinations
    select 'A', 'B' from dual;
    > A B
    > - -
    > A B
    @ rows: 1
    
    select "TABLE1"."ID1", "TABLE1"."NAME1" from "TABLE1";
    > ID1 NAME1
    > --- -----
    > 1   X
    > 2   Y
    @ rows: 2
    

提交回复
热议问题