【问题标题】:play 2.6.3 detects database from application.conf when running but not during testsplay 2.6.3 在运行时从 application.conf 检测数据库,但在测试期间不检测
【发布时间】:2017-09-02 20:33:15
【问题描述】:

我在使用 JUnit 测试来验证数据库是否与 UCanAccess 驱动程序一起正常工作时遇到了问题。当我在 IntelliJ IDEA 中正常运行服务器时,我被告知数据库池设置正确:

[info] application - Creating Pool for datasource 'default'
[info] p.a.d.DefaultDBApi - Database [default] connected at jdbc:ucanaccess://c:/Users/me/Documents/testdb.accdb

但是,当我通过 IntelliJ 运行 JUnit 测试时,出现以下错误:

Configuration error: Configuration error[Driver not found: [org.h2.Driver}]]

at play.api.Configuration$.configError(Configuration.scala:155)
at play.api.Configuration.reportError(Configuration.scala:984)
at play.api.db.DefaultDatabase$$anonfun$driver$1.apply(Databases.scala:114)
at play.api.db.DefaultDatabase$$anonfun$driver$1.apply(Databases.scala:108)
...

我认为上述错误是由 Play 默认使用默认数据库配置引起的,即 h2 数据库。

如何让 JUnit 测试识别我的数据库驱动程序而不是默认使用 h2 数据库?

测试:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import play.db.Database;
import play.db.Databases;
import play.db.evolutions.Evolution;
import play.db.evolutions.Evolutions;

import java.sql.Connection;

import static org.junit.Assert.assertTrue;


public class ApplicationTest {

    Database database;


    @Before
    public void setupDatabase() {
        // Gets default database in this case
        database = Databases.inMemory();

        System.out.println(database.getConnection());
        Evolutions.applyEvolutions(database, Evolutions.forDefault(new Evolution(
                1,
                "create table teste (id bigint not null, name varchar(255));",
                "drop table test;"
        )));
    }


    @After
    public void shutdownDatabase() {
        Evolutions.cleanupEvolutions(database);
        database.shutdown();
    }

    @Test
    public void databaseCRUD() throws Exception {
        Connection conn = database.getConnection();
        conn.prepareStatement("insert into test values (10, 'testing')").execute();
        // Make sure that there is a tenth element in the table
        assertTrue(
                conn.prepareStatement("select * from test where id = 10 and name = 'testing'")
                        .executeQuery().next()
        );
    }
}

【问题讨论】:

    标签: java junit playframework-2.0


    【解决方案1】:

    您可以使用所需的驱动程序创建数据库。 这是一个 postgres 示例:

    val dbUrl = sys.env.getOrElse("DATABASE_URL", "jdbc:postgresql://localhost:5432/app?user=user&password=password")
    val database = Databases("org.postgresql.Driver", dbUrl, "testingzzz")
    

    使用正确的 url 和驱动程序,一切顺利。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 2020-07-02
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多