When you want to run all tests against H2 in memory database a simple way to do this is to add a src/test/resources/test-ebean.properties to your project. In the test-ebean.properties you can effectively override the properties of the datasource and specify to use H2.

When an EbeanServer is created automatically via Ebean.getDefaultServer() or Ebean.getServer(name) then Ebean will look for the existence of test-ebean.properties in the classpath. If found this then typically specifies to use an in memory H2 datasource.

When programmatically creating an EbeanServer using ServerConfig and EbeanServerFactory there is a method serverConfig.loadTestProperties() which will similarly look for a test-ebean.properties file if present.

public EbeanServer getObject() throws Exception {

  ServerConfig config = new ServerConfig();

  // load test-ebean.properties if present for running tests
  // typically using H2 in memory database

  // set as default and register so that Model can be
  // used if desired for save() and update() etc

  return EbeanServerFactory.create(config);

Example test-ebean.properties




MockiEbean from ebean-mocker project provides a helper object to support mocking the EbeanServer using tools like Mockito. If you like the Play/Active record style or Ebean singleton style you can add a test dependency on ebean-mocker and use MockiEbean to enable use of Mockito and similar tools. Mocking with Ebean singleton MockiEbean from ebean-mocker provides a mechanism for using a tool like Mockito and replacing the default EbeanServer instance with a mock.

import io.ebeaninternal.server.core.DefaultServer;

  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

    // ---------------
    // '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
      // ---------------

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

MockiEbean Maven dependency