简体   繁体   中英

Spock Framework how to test spring boot application context

I use Spock Framework with Groovy scripts to test my Java application. I have 100% Test coverage in my project for all the classes that I created. However, I notice that the coverage shows that the main class called "App" is not fully tested.

Here is my App class to boot Spring application:

 package com.test.cli;

 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.context.ConfigurableApplicationContext;

 @SpringBootApplication
 public class App {
  public static void main(String[] args) {
    ConfigurableApplicationContext context = SpringApplication.run(App.class, args);

    App app = context.getBean(App.class);
    app.start();
  }

  private void start() {
    System.out.print("App started ...");
  }

 }

And this is the single test that I have for App class:

 package com.test.cli

 import com.test.cli.App
 import org.springframework.beans.factory.annotation.Autowired
 import org.springframework.boot.test.context.SpringBootTest
 import org.springframework.context.ApplicationContext
 import spock.lang.Specification


 @SpringBootTest(classes = App.class)
 class AppSpecIT extends Specification {

  @Autowired
  ApplicationContext context

  def "it should boot Spring application successfully"() {
    expect: "application context exists"
    context != null
  }

 }

You can see in this screenshot, line from 12 to 18 are not covered and I would like to fix that: 应用测试覆盖率结果

How to fully test Spring Boot application context with Spock Framework?

@SpringBootTest only instantiates the class annotated with @SpringBootApplication or any other configuration classes explicitly configured via classes . However the static main method is not executed, and should only contain the glue code SpringApplication.run(App.class, args) anyway. If you'd want to test it then you'll have to explicitly call it, but I'd advise against it you can read about why here The tragedy of 100% code coverage .

If you need something like the start method to be called after start use a org.springframework.boot.ApplicationRunner or org.springframework.boot.CommandLineRunner instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM