我正在使用 testng 进行 Spring 批处理作业编写集成测试用例。在我的应用程序中,我使用 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 以进行集成测试用例,并且我是否可以创建一个虚拟服务器来实现响应,以便测试运行得更快,没有任何异常。请帮帮我。
最佳答案
在集成测试用例中,没有直接的方法来模拟 bean。因此,替代解决方案是在您的应用程序中进行 setter 注入(inject),并在您的测试用例中更改该 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());
}
关于java - 需要在集成测试用例中模拟bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390545/