我应该测试 Spring Boot Application 的 main() 方法吗? [英] Should I test the main() method of Spring Boot Application and how?

查看:70
本文介绍了我应该测试 Spring Boot Application 的 main() 方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建 Spring Boot 应用程序时,它会生成 2 个类:

When I create Spring Boot Application it generates 2 classes:

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

第二个是测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class AppTest {

    @Test
    public void contextLoads() {
    }

}

  1. 就像您注意到 contextLoads 测试是空的一样.我应该如何为 contextLoad 提供正确的测试?它应该保持空吗?正确吗?或者我应该在里面放些东西?

更新:

  1. 为什么要保留此测试?如果我在应用程序中有更多测试,我会知道是否加载了 spring 上下文.是不是过度.

我阅读了诸如this之类的答案,但它没有给我一个明确的答案.

I readed answers like this but it didn't gave me a clear answer.

推荐答案

实际上,Spring Boot 应用程序的 main() 方法并没有像 Spring Boot 测试那样包含在单元/集成测试中不要调用 main() 方法来启动 Spring Boot 应用程序.

Actually, the main() method of the Spring Boot Application is not covered by the unit/integration tests as the Spring Boot tests don't invoke the main() method to start the Spring Boot application.

现在我认为这个帖子的所有答案 看起来有点矫枉过正.
他们想要添加对 main() 方法的测试,以使度量工具(Sonar)满意.
加载 Spring 上下文和加载应用程序需要时间.
不要为了在您的应用程序中赢得大约 0.1% 的覆盖率而在每个开发者构建中添加它.
我添加了一个关于那个的答案.

Now I consider that all answers of this post seem overkill.
They want to add a test of the main() method to make a metric tool happy (Sonar).
Loading a Spring context and loading the application takes time.
Don't add it in each developer build just to win about 0.1% of coverage in your application.
I added an answer about that.

除了您的简单示例和您引用的另一篇文章之外,如果您在其中包含一些逻辑,那么绝对可以为 main() 方法创建一个测试.它是例如,当您将特定参数传递给应用程序并在 main() 方法中处理它们时.

Beyond your simple example and the other post that you refer to, in absolute terms it may make sense to create a test for the main() method if you included some logic in. It is the case for example as you pass specific arguments to the application and that you handle them in the main() meethod.

这篇关于我应该测试 Spring Boot Application 的 main() 方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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