Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 模拟数据库驱动程序_Java_Database_Jdbc_Mocking - Fatal编程技术网

Java 模拟数据库驱动程序

Java 模拟数据库驱动程序,java,database,jdbc,mocking,Java,Database,Jdbc,Mocking,是否有某种JDBC驱动程序只是忽略数据库调用 对于开发,我正在将应用程序迁移到虚拟机。这里我只想处理GUI部分。但是应用程序向数据库发出多个请求,这甚至不允许应用程序启动。我现在不想更改应用程序代码,因为数据库几乎是耦合的 所以我想可能有一个JDBC驱动程序,它只返回空的查询结果。我自己从来没有听说过这样的驱动程序。如果找不到,可以使用类似HSQLDB的数据库。您可以将其配置为在内存表中使用,这样就不会将任何其他内容写入磁盘。但是,您必须使用不同的连接字符串。在模拟framewroks时,有一些

是否有某种JDBC驱动程序只是忽略数据库调用

对于开发,我正在将应用程序迁移到虚拟机。这里我只想处理GUI部分。但是应用程序向数据库发出多个请求,这甚至不允许应用程序启动。我现在不想更改应用程序代码,因为数据库几乎是耦合的


所以我想可能有一个JDBC驱动程序,它只返回空的查询结果。

我自己从来没有听说过这样的驱动程序。如果找不到,可以使用类似HSQLDB的数据库。您可以将其配置为在内存表中使用,这样就不会将任何其他内容写入磁盘。但是,您必须使用不同的连接字符串。

在模拟framewroks时,有一些“void”JDBC驱动程序,例如来自

但是使用它需要一些编码

这是因为当Java应用程序连接到数据库时,它以
JDBC:mysql://localhost
。系统正在搜索其中注册的驱动程序来处理此类URL,并选择正确的驱动程序。关于驱动程序支持哪种URL类型的信息包含在驱动程序本身中,模拟驱动程序不可能在其中保存所有已知的URL类型-那里没有通配符,任何列表都不会满


因此,如果您能够在应用程序连接到数据库之前调用它,它将完成这项工作。如果不是,我认为这是不可能的。不过,只要稍微修改一下驱动程序代码就可以了。。。但是,同样需要编码。

我决定编写一个自己的简单模拟驱动程序。这是非常直截了当的,做了我想做的。我可以通过配置文件切换应用程序的数据库驱动程序,这样应用程序就可以简单地使用我的驱动程序

然后我扩展了驱动程序以返回它从CSV文件解析的数据。我在google code上发布了代码,也许其他人可以使用它:

附带了可以提供的,比完整的JDBC API更容易实现的。这篇博客文章展示了如何使用MockConnection:

例如:

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<MyTableRecord> 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());

如果您使用的是Spring,请创建自己的类来实现Datasource,并且让这些方法什么都不做。

My framework Acolyte是一个经过测试的JDBC驱动程序,专门用于此类目的(模型、测试等):

它已经在几个开源项目中使用,无论是香草Java还是Scala DSL:

// Register prepared handler with expected ID 'my-unique-id'
acolyte.Driver.register("my-unique-id", handler);
// then ...
Connection con = DriverManager.getConnection(jdbcUrl);
// ... Connection |con| is managed through |handler|

如果您想进行单元测试,而不是集成测试,那么 您可以使用非常基本和简单的方法,仅使用Mockito,如下所示:

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.<Properties>any()))
                .willReturn(connection);

    }
}

我见过的另一种方法是使用从文本文件初始化的内存中hsqldb存根数据库。@Cities我知道你的意思是好的,但针对这样一个用户并留下这么多消息近乎骚扰。请不要再这样做了。标记并允许版主处理。当你编辑了你的文章以明确包含你的从属关系时,标记mods以取消删除。
@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));
}