0
  • 我用greenmail和JUNIT和mokito写了一封电子邮件测试,但是

  • 当我使用
    when(emailproperties.getUsername()).thenReturn("abc@gmail.com");

  • 显示空

  • 这是我的代码

公共类 EmailServiceImplTest {

@InjectMocks
EmailServiceImpl emailServiceImpl = new EmailServiceImpl();
@Mock
private MessageTemplateService messageTemplateService;
@Mock
private EmailProperties emailProperties;
//private static final Logger LOGGER = Logger.getLogger(EmailServiceImplTest.class);

private GreenMail greenMail;
private static final String USER_NAME = "hascode";
    private static final String EMAIL_USER_ADDRESS = "hascode@localhost";
    private static final String EMAIL_TO = "someone@localhost.com";
    private static final String EMAIL_SUBJECT = "Test E-Mail";
    private static final String EMAIL_TEXT = "This is a test e-mail.";
    private static final String LOCALHOST = "localhost";
    private static final String USER_PASSWORD = "abcdef123";

@Before
public void testSmtpInit() {
    MockitoAnnotations.initMocks(this);
    greenMail = new GreenMail(ServerSetupTest.SMTP);
    greenMail.start();
    greenMail.setUser(EMAIL_USER_ADDRESS, USER_NAME, USER_PASSWORD);
}


@Test
public void sendContactEmail() {
    MessageTemplate mock_template=new MessageTemplate();
    mock_template.setId(2);
    mock_template.setBody("Hi ${name} want to contact");
    mock_template.setSubject("Contact EMAIL");
    ContactDTO mock_Dto=new ContactDTO();
    mock_Dto.setFirstName("abc");
    mock_Dto.setLastName("xyz");
     Properties mock_props = System.getProperties();
     mock_props.put("mail.smtp.host", LOCALHOST);
     mock_props.put("mail.smtp.auth", "true");
     mock_props.put("mail.smtp.port", ServerSetupTest.SMTP.getPort());
     mock_props.put("mail.debug", "true");

    when(messageTemplateService.getMessageTemplateById("2")).thenReturn(mock_template);
    emailProperties.setAdminTo("abc@mail.com");
    when(emailProperties.getAdminTo()).thenReturn("abc@mail.com");
    when(emailProperties.getContactMsgKey()).thenReturn("2");
    when(emailProperties.getProps()).thenReturn(mock_props);
    when(emailProperties.getSenderEmail()).thenReturn(EMAIL_USER_ADDRESS);
    when(emailProperties.getSender()).thenReturn(USER_NAME);
    when(emailProperties.getHost()).thenReturn(LOCALHOST);
    when(emailProperties.getUserName()).thenReturn(EMAIL_USER_ADDRESS);
    when(emailProperties.getPassword()).thenReturn(USER_PASSWORD);


    emailServiceImpl.sendContactEmail(mock_Dto);
    MimeMessage[] messages = greenMail.getReceivedMessages();
    assertNotNull(messages);
    assertEquals(1, messages.length);


}
  • 当我调试它时显示 null 我在做什么错
4

1 回答 1

0

是的,完成。更改为@spy @Mock private EmailProperties emailProperties;

  • 并按原样设置值。
  • 15天的努力结束了一天。
于 2015-04-06T12:08:07.927 回答