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
pcavepcave 

How do I test a class that inserts objects.

I've created a class that is used to insert a new account when a contact is created (via a before insert trigger on the contact object). It works, however it will not pass testing because of the query (I think) I am using in the test method. What is the best way to test that the account was created successfully?

 

static testMethod void validateNewContactWithNewAccount() {
        Contact c = new Contact();
        c.firstname = 'Phillip';
        c.lastname = 'Cave';
        c.Temp_Organization_Name__c = 'Jackson River';
        c.Temp_Address_Line_1__c = '129 Bally Shannon Way';
        c.Temp_City__c = 'Apex';
        c.Temp_State__c = 'NC';
        c.Temp_Zip_Code__c = '27539';
        c.Temp_Overview__c = 'This is the organization overview';
        c.Temp_Website__c = 'http://www.jacksonriver.com';
        //c.Organization_Type__c = 'Pimphouse';
       
        // test our insert trigger
        insert c;
       
        Account b = [select id, name, shippingstreet, shippingcity from account where id = :c.accountid];
       
        System.assertEquals(b.id, c.accountid);
        System.assertEquals('Jackson River', b.name);
        System.assertEquals('129 Bally Shannon Way', b.ShippingStreet);
        System.assertEquals('Apex', b.ShippingCity);
    }

ThomasTTThomasTT

If you could show me/us the test error message, that would be more convenient for us...

 

So, this is just my guess.

 

You are using :c.accoutId, but when you insert Contact c, you didn't put account.id. I don't think the contact object trigger was handling and your Contact c, is the exact same object. Reocrd id is set to your Contact c by SFDC, but it's a part of specification... it doesn't mean your Contact c and what trigger gets  are the same.

 

So, How about this?

 

 

c = [select accountId from Contact where id = :c.id];
Account b = [select id, name, shippingstreet, shippingcity from account where id = :c.accountid];

System.assertEquals(b.id, c.accountid);
System.assertEquals('Jackson River', b.name);
System.assertEquals('129 Bally Shannon Way', b.ShippingStreet);
System.assertEquals('Apex', b.ShippingCity);

 

 Of course, you don't have to query Contact and Account... you can query Contact with Contact.Account.Name, etc., but you get my point, don't you?

 

ThomasTT