2

SendEmailこれが、単体テストをしようとしている私のクラスです。以下に示す行で NullPointerException が発生していますが、その理由はわかりません。

また、コードを適切に整理していますか? mockitoを正しく使用しているかどうかは正確にはわかりません。

public class StatsTest extends AbstractTestCase {
    @Mock
    MultiPartEmail MultiPartEmailMock;
    StatsTest statsTestObj;
    SendEmail mockedEmail;

    @Before
    public void setUp() throws Throwable {
        super.setUp();
        MockitoAnnotations.initMocks(this);
    }

    @Test(expected = ValidationException.class)
    public void testSendEmail() throws EmailException, IOException {
        MultiPartEmail multiPartEmailMock;
        SendEmail mockedEmail = Mockito.mock(SendEmail.class);
        Mockito.when((mockedEmail.getHtmlEmail()).send()) 
            .thenThrow(new ValidationException("Could not send the Email."));

        ^^ the line above is where the null pointer error is

        mockedEmail.sendEmail();
    }
}

テスト対象のクラスは次のとおりです。

public class SendEmail {
    private StringBuilder emailBody;
    private String senderEmail;
    private ArrayList<String> receiversEmails;
    private String emailSubject;
    private String hostName;
    private MultiPartEmail htmlEmail;

    public SendEmail(StringBuilder emailBody, String senderEmail, ArrayList<String> 
        receiversEmails, String emailSubject, String hostName, MultiPartEmail htmlEmail) {
        this.setEmailBody(emailBody);
        this.setSenderEmail(senderEmail);
        this.setReceiversEmails(receiversEmails);
        this.setEmailSubject(emailSubject);
        this.setHostName(hostName);
        this.setHtmlEmail(htmlEmail);
    }

    public void sendEmail()throws IOException, EmailException{

        htmlEmail.setHostName(getHostName());
        htmlEmail.addTo(getReceiversEmails().get(0));
        for(int i=0; i<getReceiversEmails().size(); i++){
            htmlEmail.addCc(getReceiversEmails().get(i));   
        }
        htmlEmail.setFrom(getSenderEmail());
        htmlEmail.setSubject(getEmailSubject());
        htmlEmail.setMsg((getEmailBody()).toString());
        htmlEmail.send();
    }
}
4

1 に答える 1