經過近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