如何测试 Spring-boot 应用程序的主类 [英] How to test main class of Spring-boot application

查看:41
本文介绍了如何测试 Spring-boot 应用程序的主类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 spring-boot 应用程序,其中我的 @SpringBootApplication 入门类看起来像一个标准的.因此,我为我的所有功能创建了许多测试,并将摘要发送到

我的测试类只是默认类.

@RunWith(SpringRunner.class)@SpringBootTest(classes = ElectronicGiftcardServiceApplication.class)公共类电子礼品卡服务应用测试{@测试公共无效上下文加载(){}}

那么如何在我的应用程序的入门类中测试我的主类?

解决方案

所有这些答案似乎都有些矫枉过正.
您不会为了使度量工具满意而添加测试.
加载应用程序的 Spring 上下文需要时间.不要为了在您的应用程序中赢得大约 0.1% 的覆盖率而在每个开发者构建中添加它.
此处您不只涵盖 1 个公共方法中的 1 个语句.在通常要编写数千条语句的应用程序中,它不代表任何覆盖范围.

第一个解决方法:使您的 Spring Boot 应用程序类没有在内部声明 bean.如果你有它们,把它们移到一个配置类中(让它们仍然被单元测试覆盖).然后忽略 中的 Spring Boot 应用程序类测试覆盖配置.

第二种解决方法:如果您确实需要覆盖 main() 调用(例如出于组织原因),请为其创建一个测试,但创建一个集成测试(由持续集成工具和不是在每个开发人员构建中)并清楚地记录测试类的目的:

import org.junit.Test;//添加测试类仅用于覆盖应用程序测试未覆盖的 main() 调用.公共类 MyApplicationIT {@测试公共无效主(){MyApplication.main(new String[] {});}}

I have a spring-boot application where my @SpringBootApplication starter class looks like a standard one. So I created many tests for all my functionalities and send the summary to sonarqube to see my coverage.

For my starter class Sonarqube tells me that I just have 60% coverage. So the average coverage is not good as expected.

My Test class is just the default one.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ElectronicGiftcardServiceApplication.class)
public class ElectronicGiftcardServiceApplicationTests {

    @Test
    public void contextLoads() {
    }
}

So how can I test my main class in the starter class of my application?

解决方案

All these answers seem overkill.
You don't add tests to make a metric tool happy.
Loading a Spring context of the application takes time. Don't add it in each developer build just to win about 0.1% of coverage in your application.
Here you don't cover only 1 statement from 1 public method. It represents nothing in terms of coverage in an application where thousands of statements are generally written.

First workaround : make your Spring Boot application class with no bean declared inside. If you have them, move them in a configuration class (for make them still cover by unit test). And then ignore your Spring Boot application class in the test coverage configuration.

Second workaround : if you really need to to cover the main() invocation (for organizational reasons for example), create a test for it but an integration test (executed by an continuous integration tool and not in each developer build) and document clearly the test class purpose :

import org.junit.Test;

// Test class added ONLY to cover main() invocation not covered by application tests.
public class MyApplicationIT {
   @Test
   public void main() {
      MyApplication.main(new String[] {});
   }
}

这篇关于如何测试 Spring-boot 应用程序的主类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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