如何从命令行运行位于 JAR 文件中的测试类?

huangapple go评论70阅读模式
英文:

How to run a test class in a jar file from command line?

问题

我的SpringBoot项目结构如下:

如何从命令行运行位于 JAR 文件中的测试类?

项目中没有主类,我已经将项目编译成了一个jar文件。

现在,我想要从命令行运行最后一行屏幕截图中显示的测试类Send1000EmailsIn24hours中名为"testEmailSending"的方法,该类位于截图中最后一行。

我之所以想要在jar文件中运行这个测试,是因为整个项目只是一个测试。但是我认为,既然这只是一个测试,所以不应该将代码放在main类中,相反,将其放在一个测试类中会更好。

我不确定这样做是否正确。我是否应该将测试代码仅放在主类中?

英文:

The structure of my SpringBoot project is:

如何从命令行运行位于 JAR 文件中的测试类?

There is no main class, and I have compiled the project into a jar file.

Now I want to run a method named "testEmailSending" in the test class shown in the very last line of the screenshot, Send1000EmailsIn24hours, from the jar file from command line.

The reason why I want to run this test in a jar file is that the whole project is just a test, but I think that since it is a test, so I shouldn't put the code in the main class, instead, putting it in a test would be better.

I am not sure if this is correct. Should I put the code for testing just in the main class?

答案1

得分: 1

根据Alexei Kovalev的暗示,你绝不应该这样做。
测试代码就是测试代码。良好的实践是永远不要将其包含在应用程序中,而Maven/Gradle默认会遵守这一原则。
对于Spring Boot,建议你在框架提供的工具范围内执行测试和集成测试:通过使用@SpringBootTest注解你的测试类,可以实现这一目标,它会加载一个Spring上下文,就像运行你的jar文件一样。
如果除了这些类型的测试之外,你需要对一个JAR文件执行测试,当然可以这样做。在某种程度上,这是有意义的,因为一个JAR文件可能具有一些不同的打包差异,可以进行测试。但你应该为此编写少量的测试用例。因为打包一个完整的Spring Boot应用程序是一个耗时的过程,而且因为你无法享受Spring Boot提供的所有测试设施。
总体的想法是:

  • 编写集成测试(JUnit作为运行器就足够了),这些测试不会打包到应用程序中,并调用组件(通过Web请求进行API/控制器调用)或检查这些副作用(用于批处理处理)。
  • 以jar文件形式运行应用程序。
  • 运行集成测试。
英文:

As Alexei Kovalev implies, you never want to do that.
Test code is test code. Good practice is to never include it in the application and maven/gradle honor that by default.
With spring boot, you are advised to execute tests and integration test in the frame of the tools provided by the framework : Annotating your test with@SpringBootTest achieves that goal by loading a spring context as you will do by running your jar.
If besides these kinds of test you need to perform tests on a JAR, you may of course do that. In a some measure, it may make sense since a JAR may have some packaging differences that could be tested. But you should write few tests for that. Because packaging a full spring boot application is a slow process and also because you could not benefit from all test facilities provided by Spring Boot.
The overall idea for that :

  • write integration tests (JUnit is enough as runner) that are not packaged in the application and that calls the component (via web requests for api/controllers) or check these side effects (for batch processings).
  • run the application as a jar
  • run integration tests

huangapple
  • 本文由 发表于 2020年7月25日 08:43:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63083119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定