簡體   English   中英

ReflectionTestUtils 在下面的代碼中是如何工作的

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM