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

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

问题描述

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



我的Test类只是默认类。

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

@Test
public void contextLoads(){
}
}

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

解决方案

所有这些答案看起来都有些过分。

您不需要添加测试来使度量工具满意。

加载Spring的上下文应用程序需要时间。不要在每个开发人员构建中添加它只是为了赢得应用程序中大约0.1%的覆盖率。

这里你不只覆盖1个声明来自1个公共方法。它在应用程序的覆盖范围方面没有任何意义,其中通常会编写数千个语句



第一种解决方法:使你的Spring Boot应用程序类内部没有声明bean。如果您有它们,请在配置类中移动它们(使它们仍然通过单元测试覆盖)。然后在中忽略您的Spring Boot应用程序类测试覆盖率配置。



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

  import org.junit.Test; 

//仅添加测试类以涵盖应用程序测试未涵盖的main()调用。
公共类MyApplicationIT {
@Test
public void main(){
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天全站免登陆