10

When using @DataJpaTest, how can I configure the test class to run with the bits needed to handle http requests for the H2 console?

I am running a Spring Boot 2.0 test that uses H2. I want to set a breakpoint in a test and view the contents of a table in H2. However, when the test stops at the breakpoint and I point my browser to http://localhost:8080/h2-console, the result is a blank page with the text "localhost didn’t send any data". So it appears that either the test is running without the bits needed to handle the http request for the H2 console or the URL I'm using is wrong.

Note: when I run the test, the console indicates that the embedded H2 database is successfully started, so I'm confident H2 is actually running.

Here are my test class annotations:

@ExtendWith(SpringExtension.class)

@DataJpaTest

@TestInstance(TestInstance.Lifecycle.PER_CLASS)

I read an article suggesting to include devtools in my pom, but that did not solve my problem.

Edit: The crux of my problem seems to be that I cannot figure out how to configure a test to include both an embedded test database and a running servlet. If I annotate the test class with both @DataJpaTest and @SpringBootTest(webEnvironment = ...), the test crashes due to a missing ServletWebServerFactory bean. Removing @DataJpaTest fixes the missing bean problem, but I no longer have an embedded test database. Using only @DataJpaTest fails to start a servlet

Mark Norman
  • 2,271
  • 1
  • 13
  • 17

1 Answers1

0

The H2 Console is a web application which is only started under some conditions:

  • You are developing a servlet-based web application.
  • com.h2database:h2 is on the classpath.
  • You are using Spring Boot’s developer tools.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-sql-h2-console

If you are running a test and not starting up a ServletContext the h2 Console wouldn't start up either.

Janning Vygen
  • 8,877
  • 9
  • 71
  • 102
  • 1
    I cannot find a way to configure a test to use a test H2 database and to also include a running servlet. If I annotate the test class with both `@DataJpaTest` and `@SpringBootTest(webEnvironment = ...)`, the test crashes due to a missing ServletWebServerFactory bean. Removing `@DataJpaTest` fixes the missing bean problem, but I no longer have an embedded test database. Using only `@DataJpaTest` fails to start a servlet. – Mark Norman Oct 03 '18 at 19:15