Gurnor
Gurnor

Reputation: 339

How to write testcase for trigger?

I have a trigger which copies the billing street address from the related Account to the other streets address on the related Contact. I wrote this trigger from reading materials online is this correct? Is there better way to write it?

Public class iTestClass {

    public static testmethod void test() 
      {
            Contact objContact1;
            Contact objContact2;

            objContact1 = New Contact();
            objContact1.OtherStreet = '123 lane';
            objContact1.OtherCity = 'Washington';
            objContact1.OtherState = 'OR';
            objContact1.OtherCountry = 'USA';
            objContact1.OtherPostalCode = '12122';

            objContact2 = New Contact();
            objContact2.OtherStreet = '232 st.';
            objContact2.OtherCity = 'cleveland';
            objContact2.OtherState = 'OH';
            objContact2.OtherCountry = 'USA';
            objContact2.OtherPostalCode = '166030';
        }
    }

Upvotes: 0

Views: 329

Answers (1)

Matt Lacey
Matt Lacey

Reputation: 8255

You're on the right lines, but a) you're not inserting the contact records, and b) you need to insert an account first, then set the account ID on those contacts before you insert them.

// before creating the contacts create an account
Account sAcct = new Account();
sAcct.Name = 'Test Account';
sAcct.BillingStreet = '1 Some Street'; // I forget the name of the field!
// etc.
insert sAcct;

// then on your contacts do this:
objContact1.Account = sAcct.Id;

// then insert them at the end to fire the trigger
insert objContact1;

Upvotes: 1

Related Questions