在 Spring 应用程序中运行 junit 测试时访问 h2 Web 控制台 [英] Access to h2 web console while running junit test in a Spring application

查看:20
本文介绍了在 Spring 应用程序中运行 junit 测试时访问 h2 Web 控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 Spring 应用程序,我需要在从 Web 浏览器运行 JUnit 测试时检查我的 H2 内存数据库.

I'm building a Spring application and I need to inspect my H2 in-memory database while I'm running my JUnit tests from a web browser.

在我的 Spring 配置中,我有一个 bean,它负责创建我的数据库模式并用一些数据填充它,这些数据将在我的 JUnit 测试中使用.我还在我的测试上下文中添加了一个 bean,它创建了一个 Web 服务器,我最终将在其中查找我的数据.

In my Spring configuration I have a bean which is responsible of creating my database schema and populating it with some data which will be used within my JUnit tests. I've also added a bean in my test context which creates a web server where I eventually will look for my data.

<bean id="org.h2.tools.Server-WebServer" class="org.h2.tools.Server"
    factory-method="createWebServer" init-method="start" lazy-init="false">
    <constructor-arg value="-web,-webAllowOthers,-webPort,11111" />
</bean>

一切似乎都很好,因为数据库已正确填充,因为我可以从我的 JUnit 测试中访问它的数据,而 H2 服务器仅在我处于测试阶段时运行(我可以知道,因为如果我尝试访问my_ip:111111 在调试我的测试之前我无法连接,但我可以在开始测试后连接).

Everything seems ok because the database is populated properly since I can access to its data from my JUnit tests and H2 Server only runs while I'm in my test-phase (I can know that, because if I try to access to my_ip:111111 before debugging my tests I cannot connnect but I can connect afterwards once I've started my tests).

无论如何,如果我从 Web 浏览器打开 H2 控制台,则不会显示任何架构.有什么想法吗??

Anyway If I open my H2 console from a web browser no schema is shown in it. Any ideas??

非常感谢!!

推荐答案

由于这可能是一个测试调试功能,您可以在运行时使用 @Before 添加它:

As this is probably going to be a test-debugging feature, you can add it at runtime with your @Before:

import org.h2.tools.Server;

/* Initialization logic here */

@BeforeAll
public void initTest() throws SQLException {
    Server.createWebServer("-web", "-webAllowOthers", "-webPort", "8082")
    .start();
}

然后连接到http://localhost:8082/

注意:除非您需要将此代码作为 CI 构建的一部分运行,否则您需要在完成调试后删除此代码

Note: unless you need this to run as part of your CI build, you'll need to remove this code when you're finished debugging

这篇关于在 Spring 应用程序中运行 junit 测试时访问 h2 Web 控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆