function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Wei Dong 10Wei Dong 10 

Why cannot I get the Mailing property values from Contact?

Hi,

You know that One Case has one Contact in default. But there's an interesting thing——

Here's my test class:
@isTest
public class SampleTest {
    @isTest
    public static void testForMailingValidation() {

        Account newAccount = new Account();
        newAccount.Name = 'dongwei';
        insert newAccount;

        Contact newContact = new Contact();
        newContact.AccountId = newAccount.Id;
        newContact.Salutation = 'Mr.';
        newContact.LastName = 'TEST';
        newContact.Email = 'testLetter@pwc.com';
        newContact.MailingStreet = 'testStreet';
        newContact.MailingCity = 'testCity';
        newContact.MailingState = 'testState';
        newContact.MailingPostalCode = 'testPostalCode';
        newContact.MailingCountry = 'testCountry';
        insert newContact;

        System.debug('Test for mailing address===' + newContact.MailingAddress);  // why null?
        System.debug('Test for mailing MailingCity===' + newContact.MailingCity); // we have a real value 'testCity'

        Case newCase = new Case();
        newCase.ContactId = newContact.Id;
        insert newCase;

        List<Case> cases = [
                SELECT Contact.MailingCity
                FROM Case
                WHERE Id = :newCase.Id
                LIMIT 1
        ];
        // Why I got null here?
        System.debug('Test for mailing MailingCity after insert of Case===' + cases[0].Contact.MailingCity);
    }
}

As my comment, I REALLY don't know what the relationship between MailingAddress and MailingCity,MailingPostCode……ect. 
To my surprise, why I get null if I want to fetch the value through the Contact from case???
How to solve that?
Abdul KhatriAbdul Khatri
Before line 22 add the following line
newContact = [SELECT Id, MailingAddress, MailingCity FROM Contact LIMIT 1];