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 等都将被初始化?
更新
看来我已经找到了解决方案:
应用测试类
@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)
| 归档时间: |
|
| 查看次数: |
3108 次 |
| 最近记录: |