test-ebean.properties

当您希望针对内存数据库中的H2运行所有测试时,一种简单的方法是向您的项目添加src/test/resources/test-ebean.properties。在test-ebean.properties中,您可以有效地覆盖数据源的属性并指定使用H2

当通过Ebean.getDefaultServer()Ebean.getServer(name)自动创建 EbeanServer 时,Ebean 将在类路径中查找 test-ebean.properties 的存在。如果找到,则通常指定使用内存H2数据源。

当使用ServerConfigEbeanServerFactory以编程方式创建 EbeanServer 时,有一个方法serverConfig.loadTestProperties(),如果存在,它将类似地查找 test-ebean.properties 文件。

@Override
public EbeanServer getObject() throws Exception {

  ServerConfig config = new ServerConfig();
  config.setName("db");
  config.loadFromProperties(properties);
  ...

  // load test-ebean.properties if present for running tests
  // typically using H2 in memory database
  config.loadTestProperties();

  // set as default and register so that Model can be
  // used if desired for save() and update() etc
  config.setDefaultServer(true);
  config.setRegister(true);

  return EbeanServerFactory.create(config);
}

示例 test-ebean.properties

ebean.db.ddl.generate=true
ebean.db.ddl.run=true

datasource.db.username=sa
datasource.db.password=
datasource.db.databaseUrl=jdbc:h2:mem:tests
datasource.db.databaseDriver=org.h2.Driver

MockiEbean

MockiEbean来自ebean-mocker项目,它提供了一个帮助对象,用于支持使用诸如 Mockito之类的工具模拟 EbeanServer。如果您喜欢 Play/Active 记录样式或 Ebean 单例样式,则可以添加对 ebean-mocker 的测试依赖项,并使用 MockiEbean 来启用 Mockito 和类似工具。使用 Ebean 单例MockiEbean进行模拟,ebean-mocker 提供了一种使用类似 Mockito 的工具并用模拟替换默认 EbeanServer 实例的机制。

...
import io.ebeaninternal.server.core.DefaultServer;
...

  @Test
  public void testWithMockito() {

    EbeanServer defaultServer = Ebean.getServer(null);
    assertTrue("is a real EbeanServer", defaultServer instanceof DefaultServer);

    Long someBeanId = Long.valueOf(47L);

    // Use Mockito to create a mock for the EbeanServer interface
    EbeanServer mock = Mockito.mock(EbeanServer.class);

    // setup some required behaviour
    when(mock.getBeanId(null)).thenReturn(someBeanId);

    // ---------------
    // 'register' the mock instance into Ebean
    // this becomes the 'default EbeanServer' until
    // mockiEbean.restoreOriginal() is called
    // ---------------
    MockiEbean mockiEbean = MockiEbean.start(mock);
    try {

      // Ebean singleton 'default server' now returns the mock instance
      EbeanServer server = Ebean.getDefaultServer();

      // always returns the someBeanId setup by Mockito
      Object beanId = server.getBeanId(null);

      assertEquals(someBeanId, beanId);

    } finally {
      // ---------------
      // restore the original defaultServer instance
      // ---------------
      mockiEbean.restoreOriginal();
    }

    EbeanServer restoredServer = Ebean.getDefaultServer();
    assertTrue("is a real EbeanServer", restoredServer instanceof DefaultServer);
  }

  

MockiEbean Maven 依赖项

<dependency>
  <groupId>io.ebean</groupId>
  <artifactId>ebean-mocker</artifactId>
  <version>13.6.0</version>
  <scope>test</scope>
</dependency>