jeudi 30 juillet 2015

How to test non-public methods?

I am learning Scala and wrote Email class which looks like

class Email(emailConfigName: String) {
  private val emailConfig = ConfigFactory.load(emailConfigName) getConfig ("email")

  def notifySupportForTenant(symbolicName: String) {
    val emailMessage: Message = constructEmailMessage(symbolicName)
    Transport.send(emailMessage)
  }

  def constructEmailMessage(symbolicName: String): Message = {
    val message = createMessage(emailConfig getString ("shn.mail.smtp.host"))
    message setFrom (new InternetAddress(emailConfig getString ("shn.mail.from")))
    // todo: should come from API (sent by client)
    message setSentDate (new Date())
    message setSubject (emailConfig getString ("shn.mail.subject") replace("TENANT_ID", symbolicName))
    message setContent(emailConfig getString ("shn.mail.body"), "text/html")
    message.setRecipients(Message.RecipientType.TO, getMessageRecipients(emailConfig getString ("shn.mail.recipient")))
    message
  }

  private def createMessage(smtpHost: String): Message = {
    val properties = new Properties()
    properties put("mail.smtp.host", smtpHost)
    val session = Session.getDefaultInstance(properties, null)
    return new MimeMessage(session)
  }

  private def getMessageRecipients(recipient: String): Array[Address] = {
    // had to do the asInstanceOf[...] call here to make scala happy
    val addressArray = buildInternetAddressArray(recipient).asInstanceOf[Array[Address]]
    if ((addressArray != null) && (addressArray.length > 0)) addressArray
    else
      throw new IllegalArgumentException("no recipients found to send email")
  }

  private def buildInternetAddressArray(address: String): Array[InternetAddress] = {
    // could test for a null or blank String but I'm letting parse just throw an exception
    return InternetAddress.parse(address)
  }
}

I want to test this class's public API, notifySupportForTenant but this is not good for Unit Test since it also calls Transport.send(emailMessage) which will send the email.

All I am interested in testing if the message is constructed correctly. Which means I need to test constructEmailMessage

In order to test this, I had to make this public which is also exposed as public interface, which I do not prefer

What can I do?

Aucun commentaire:

Enregistrer un commentaire