[英]SpringBoot : How ReflectionTestUtils.setFields work?
[英]How does ReflectionTestUtils work in the below code
@Service
public class EmailService {
private JavaMailSenderImpl mailSender;
@PostConstruct
protected void init() {
mailSender= new JavaMailSenderImpl();
mailSender.setHost("some.server.com");
mailSender.setPort("25");
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
}
public void sendEmail(String recipient, String subject, String message){
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom("someone@somewhere.com");
simpleMailMessage.setTo(recipient);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(message);
mailSender.send(simpleMailMessage);
}
}
上面的代碼是發送電子郵件。
public class EmailServiceTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@InjectMocks
private EmailService emailService;
@Mock
private JavaMailSenderImpl mailSender;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testEmail(){
exception.expect(MailSendException.class);
ReflectionTestUtils.setField(emailService, "mailSender", mailSender);
emailService.sendEmail("me.com", "test", "this is a unit test");
}
}
我已經編寫了一個測試用例,我希望郵件發送失敗,但是在 EmailServicetest testEmail() 中我沒有收到任何錯誤,因為服務器不存在,所以我希望 MailSendException。 誰能告訴我可能是什么原因?
ReflectionTestUtils.setField
用你的 mock 替換mailSender
中的 mailSender 字段。
由於沒有為mailSender
指定行為,因此此模擬上的每個方法調用都會以默認行為響應 - 返回類型的默認值。 對於 void 方法,方法調用無效。 這就是為什么你沒有例外。
您需要使用Mockito.when
指定預期行為
最重要的是:
通過@Autowired
構造函數設置JavaMailSenderImpl.mailSender
,而不是通過@PostConstruct
方法。 這樣,您將郵件服務器配置外部化並方便測試(例如,不需要反射)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.