我正在通过使用testng进行春季批处理工作来编写集成测试用例。在我的应用程序中,我使用Google API作为地址,并使用Mail Sender发送电子邮件。在我的集成测试用例中,在测试运行期间需要一段时间才能进行连接,最后发送异常看上去很丑陋且耗时。
我尝试模拟bean,但是我不知道如何在集成测试用例中精确地完成操作。
Google Api Code:
@Slf4j
public final class GoogleApiContext {
private static GeoApiContext context;
private GoogleApiContext() {
}
public static GeoApiContext getGeoApiContext(String apiKey, int maxQps) {
if (context == null) {
log.info("Creating google api context having key - {} and maxQps - {}", apiKey, maxQps);
context = new GeoApiContext.Builder().apiKey(apiKey).queryRateLimit(maxQps).build();
}
return context;
}
}
Mail Sender Code:
@Override
public Boolean sendMailWithAttachment(final MailBo mailBo, final String pathToAttachment, final String fileName) {
try {
log.info("Sending Email {}", mailBo);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(mailBo.getTo());
helper.setSubject(mailBo.getSubject());
helper.setText(mailBo.getText());
File file = new File(pathToAttachment);
helper.addAttachment(fileName, file);
mailSender.send(message);
log.info("Mail sent successfully");
return true;
} catch (MessagingException e) {
log.info("Mail Exception {}", e);
return false;
}
}
Integration Test Case:
@SpringBootTest(
classes = {ApplicationLauncher.class, BatchConfiguration.class, BatchTestConfig.class})
public class PostalJobTest extends AbstractTestNGSpringContextTests {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
JobLauncher dataloadJobLauncher;
@Autowired
private Job postalJob;
@Test
public void testPostalJob_valid_response() throws Exception {
String fileName = getFileName(FileLocation.POSTAL_VALID, FileLocation.TEMP_POSTAL_VALID);
JobParametersBuilder jobParametersBuilder = getJobParametersBuilder(fileName);
jobLauncherTestUtils.setJob(postalJob);
jobLauncherTestUtils.setJobLauncher(dataloadJobLauncher);
JobExecution jobExecution =
jobLauncherTestUtils.launchJob(jobParametersBuilder.toJobParameters());
Assert.assertEquals(jobExecution.getStatus(), BatchStatus.STARTING);
Thread.sleep(2000);
while (jobExecution.isRunning()) {
}
Assert.assertEquals(jobExecution.getStatus(), BatchStatus.COMPLETED);
}
我想模拟GeoApiContext和MailSender进行集成测试用例,如果我可以创建一个虚拟服务器来实现响应,以便测试运行更快而没有任何异常。
答案 0 :(得分:1)
在集成测试用例中,没有直接方法可以模拟bean。因此,另一种解决方案是在应用程序中进行setter注入,并在测试用例中更改该bean。
// mail service
private JavaMailSender mailSender;
@Autowired
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
// test file
@Autowired
private MailServiceImpl mailService;
@BeforeClass
public void setJob() {
jobLauncherTestUtils.setJob(postalJob);
mailService.setMailSender(new JavaMailSenderTestImpl());
}