经过近8年的时间,我不得不粉碎我的Spring知识,只要我不必编写单元测试,事情就很好。我有以下的单元测试将测试我的服务之一,当我试图运行它,它会失败的:运行单元测试时出现弹簧启动错误
org.springframework.beans.factory.UnsatisfiedDependencyException
,这是不能够解决eMailNotificationService服务!
因此,这里是我的单元测试:
@ActiveProfiles("test")
@ComponentScan(basePackages = {"com.middleware.service.email", "it.ozimov.springboot.templating.mail"})
@RunWith(SpringRunner.class)
public class EMailNotificationServiceTest {
@Autowired()
private EMailNotificationService eMailNotificationService;
@MockBean(name = "emailService")
private EmailService emailService;
@Test
public void sendResetPasswordEMailNotification() {
System.out.println(eMailNotificationService);
// TODO: complete the test
}
}
的EMailNotificationService是下面这在com.middleware.service.email包中定义:
@Service()
@Scope("singleton")
public class EMailNotificationService {
private static Log logger = LogFactory.getLog(EMailNotificationService.class);
@Value("${service.email.sender}")
String senderEMail;
@Value("${service.email.sender.name}")
String senderName;
@Value("${service.email.resetPassword.link}")
String resetPasswordLink;
@Autowired
public EmailService emailService;
public void sendResetPasswordEMail(List<EMailUser> userList) {
List<String> allEMails = userList.stream()
.map(EMailUser::getUserEMail)
.collect(Collectors.toList());
userList.stream().forEach(emailUser -> {
final Email email;
try {
email = DefaultEmail.builder()
.from(new InternetAddress(senderEMail, senderName))
.to(Lists.newArrayList(new InternetAddress(emailUser.getUserEMail(), emailUser.getUserName())))
.subject("Reset Password")
.body("")//Empty body
.encoding(String.valueOf(Charset.forName("UTF-8"))).build();
// Defining the model object for the given Freemarker template
final Map<String, Object> modelObject = new HashMap<>();
modelObject.put("name", emailUser.getUserName());
modelObject.put("link", resetPasswordLink);
emailService.send(email, "resetPasswordEMailTemplate.ftl", modelObject);
} catch (UnsupportedEncodingException | CannotSendEmailException ex) {
logger.error("error when sending reset password EMail to users " + allEMails, ex);
}
});
}
}
我怎样写我的单元测试,使我的服务注入/自动装配?
是有可能,是不是为您的配置文件创建这个bean '测试'? – wawek