【问题标题】:How to mock the dtabase in J2EE for junit without spring boot如何在没有 Spring Boot 的情况下在 J2EE 中为 junit 模拟数据库
【发布时间】:2020-10-21 17:30:30
【问题描述】:

我正在开发一个基于纯 Java/J2EE servlet 的遗留项目。没有spring等框架。它建立在蚂蚁之上。 现在我想将 junit 与我的项目集成,我能够集成,但我想模拟数据库并在模拟的数据库连接中运行测试用例。 我认为在 Spring Boot 中,我们可以使用 H2 数据库轻松做到这一点。但我面临的唯一挑战是我们没有使用弹簧靴。 我能够模拟这些函数并运行测试用例,但我需要的是模拟整个数据库并在我的模拟数据库上运行测试类。 任何线索我可以如何实现这一点,或者它是否可行?

【问题讨论】:

    标签: java servlets junit mockito h2


    【解决方案1】:

    你可以在纯java中运行h2 database,因为它是写在里面的。见H2 Documentation


    在纯java中启动h2 database服务器并运行sql脚本

    1. 要启动tcp-server,您可以使用Server 工具:

      Server server = Server.createTcpServer();
      server.start();
      

      要启动一个网络服务器(使用h2-console),您可以添加:

      Server server = Server.createWebServer();
      server.start();
      
    2. 要打开JdbcConnectionRunScript,你可以这样写:

      private void createTables(String url, String username,
                                String password, File script)
              throws SQLException, IOException {
      
          Properties info = new Properties();
          info.put("user", username);
          info.put("password", password);
      
          JdbcConnection connection = new JdbcConnection(url, info);
          InputStreamReader reader =
                  new InputStreamReader(new FileInputStream(script));
      
          RunScript.execute(connection, reader);
      
          reader.close();
          connection.close();
      }
      

    另见:

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 2021-12-09
      • 2020-06-03
      • 2020-12-23
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      相关资源
      最近更新 更多