在另一个进程(VM)中启动Java main
我有一个服务器客户端项目,出于测试目的,我想在一个全新的进程中启动服务器。问题是,我的项目中只有一个 main() 方法,没有 jar。所以我的猜测是这样的
Runtime.getRuntime().exec("javac MyServer.java");
Runtime.getRuntime().exec("java class MyServer");
,但我真的不确定它,而且我也不完全喜欢为每个测试用例启动 javac 的需要。
我应该如何进行?
编辑
我想在@Before
方法中启动该进程并在@After
中销毁它。它必须自动运行,因此手动打开服务器不是一个选择。我正在寻找一种消除服务器类编译的方法。但现在我想也没有别的办法了。
I have a server client project and for testing purposes I want to start the server in a whole new process. The problem is, I have just a main() method in project, no jar. So my guess would be something like
Runtime.getRuntime().exec("javac MyServer.java");
Runtime.getRuntime().exec("java class MyServer");
But I am really not sure about it and also I don't exactly like the need to start javac for each test case.
How should I proceed?
EDIT
I want to start the process in the @Before
method and destroy it in @After
. It has to run automatically, so manual turning on the server is not an option. What I was looking for is a way to eliminate compilation of the server class. But now I guess there is no other way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果这是出于测试目的,只需从命令行启动其他进程或使用 Eclipse 来处理它。在 Eclipse 中,同一个项目可以有多个 main() 入口点。当您希望运行应用程序时,您可以创建一个运行/调试配置,说明您希望调用哪个入口点。因此,您可以为客户端定义一个,为服务器定义一个,然后单击按钮即可运行它们。
扩展:
先决条件 - 在执行任何操作之前,首先将项目导入 Eclipse。
Eclipse 还有一个调试视角,您可以在其中停止/暂停正在运行的进程、设置断点等等。它甚至可以同时调试多个事物,因此您可以在调试中启动客户端和服务器,并在调用的任一侧设置断点。
If this is for testing purposes, just launch the other process from the command line or use Eclipse to take care of it. In Eclipse the same project can have multiple main() entry points. When you wish to run the app you create a run / debug configuration that says which entry point you wish to invoke. So you could define one for the client and one for the server and run them with a button click.
Expanded:
Prerequisite - import your project into Eclipse first before doing any of this.
Eclipse also has a debug perspective where you can stop / pause running processes, set breakpoints and whatnot. It can even debug more than one thing simultaneously so you could launch both client and server in debug and set breakpoints either side of the call.
Java 允许您像这样进行系统调用。
这将允许您启动另一个 java 进程。如果需要,进程还具有获取该进程的输出的方法。
Java allows you to make system calls like so.
This would allow you to start another java process. Process also has methods to get the output of that process if you need it.
看看 JUnit,我认为你想要做的是针对你的客户端运行一系列测试,服务器正在运行。您可以通过编写一个 JUnit 测试来完成此任务,该测试使用 @Before 注释在每次测试之前运行设置方法。例如:
Take a look at JUnit, what I think you want to do is run a series of tests against your client, with a server running. You can accomplish this by writing a JUnit test which makes use of the @Before annotation to run a setup method before each test. For example: