运行Spring Boot Unit测试忽略CommandLineRunner

时间:2018-01-11 01:06:31

标签: unit-testing spring-boot

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

App.class

@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());
  }
}

ReportServiceTest.class

@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());
  }

我需要做的是在测试中运行时会忽略CommandLineRunner但是所有ApplicationContext,JPA等都将被初始化?

更新

我似乎找到了解决方案:

  • 将@Profile(“!test”)添加到App.class
  • 在测试目录中创建了新的AppTest.class,我只在没有CommandLineRunner的情况下初始化SpringApplication
  • 将@ActiveProfile(“test”)添加到ReportServiceTest.class

AppTest.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);
  }
}

0 个答案:

没有答案