Search code examples
javajunitportgreenmail

JUnit refers to same var value


I'm writing a test like this

public String cc = "";

@Test
public void testSendMailWithMissingData() throws MessagingException {

    String sender = "[email protected]";
    String receiver = "[email protected]";
    String subject = "";
    String content = "";

    javaMailSenderImpl.setPort(greenMail.getSmtp().getPort());
    iMailService.sendMail(sender, receiver, subject, content, cc);

    MimeMessage[] emails = greenMail.getReceivedMessages();
    assertEquals(subject, emails[0].getSubject());
    ......
    }

@Test
public void testSendMailWIthData() throws MessagingException {

    String sender = "[email protected]";
    String receiver = "[email protected]";
    String subject = "test_subject";
    String content = "test_content";
    cc = "[email protected]";

    javaMailSenderImpl.setPort(greenMail.getSmtp().getPort());
    iMailService.sendMail(sender, receiver, subject, content, cc);

    MimeMessage[] emails2 = greenMail.getReceivedMessages();
    assertEquals(cc, InternetAddress.toString(emails2[0].getRecipients(Message.RecipientType.CC)));

     }

but I get in testSendMailWIthData that exspected cc is [email protected] but is null. Why? Is it because I use same port? Why I cant use two different String values in two different @Test?

Help

JUNIT log:

java.lang.AssertionError: expected:<[email protected]> but was:<null>
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:743)
    at org.junit.Assert.assertEquals(Assert.java:118)
    at org.junit.Assert.assertEquals(Assert.java:144)
    ...

Solution

  • In testSendMailWIthData() can you retrieve all the fields of each email in emails2[]?

    I think you are receiving the email sent from the first test as well in the second test. In the first test, you have sent an email with CC null/absent. That could be the reason you are getting null.

    I recommend you to print all email fields like sender, receiver, subject, content, and cc to confirm this. If that's the case, to avoid the issue either use different server/port in each test OR while asserting identify the correct email first (say by sender and keep sender email address different in each test) and then assert remaining fields.

    Another option could be - first delete all emails from a specific sender ([email protected]) as a pre-step (@Before) in each test and then proceed with send, retrieve and assert.