运行 Spring Boot 单元测试忽略 CommandLineRunner

Vik*_* V. 8 unit-testing spring-boot

我正在尝试编写 Spring Boot 单元测试,但在运行单元测试时运行整个应用程序的 CommandLineRunner 有一些问题。

应用程序类

@SpringBootApplication
@Profile("!test")
public class App implements CommandLineRunner {

  @Autowired
  private ReportService reportService;

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(App.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {

    if (args.length == 0)
      reportService.generateReports();

    if (args.length > 0 && args[0].equals("-p"))
      for (Report report : reportService.showReports())
        System.out.println(report.getId() + " : " + report.getTimestamp());
  }
}
Run Code Online (Sandbox Code Playgroud)

报告服务测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
@ActiveProfiles("test")
public class ReportServiceTest {

  @Autowired
  private ReportRepository reportRepository;

  @Autowired
  private ReportService reportService;

  @Test
  public void testShowReports() {
    List<Report> expectedReports = new ArrayList<>(3);
    for(int i = 0; i< 3; i++) {
      expectedReports.add(reportRepository.save(new Report()));
    }

    List<Report> actualReports = reportService.showReports();
    assertEquals(expectedReports.size(), actualReports.size());
  }
Run Code Online (Sandbox Code Playgroud)

我需要做什么才能在测试中运行时 CommandLineRunner 将被忽略,但所有 ApplicationContext、JPA 等都将被初始化?

更新

看来我已经找到了解决方案:

  • 将 @Profile("!test") 添加到 App.class
  • 在测试目录中创建了新的 AppTest.class,其中我仅初始化 SpringApplication 而没有 CommandLineRunner
  • 将 @ActiveProfile("test") 添加到 ReportServiceTest.class

应用测试类

@SpringBootApplication
@Profile("test")
public class AppTest {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(AppTest.class);
    app.setLogStartupInfo(false);
    app.run(args);
  }
}
Run Code Online (Sandbox Code Playgroud)