繁体   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