我正在尝试编写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等都将被初始化?
更新
我似乎找到了解决方案:
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);
}
}