Pages

Friday, March 13, 2015

My First Working Apex Test Class

Finally - after much-needed help & Google - a working Apex test class surrounding the working SOQL query I made weeks ago.

It's not a full test suite - it doesn't deal with updates where an Opportunity record type gets changed or an Opportunity Primary Contact Role gets changed - but it's a start. It definitely compares a value against the results of my SOQL query.

My SOQL query counts the # of "Admission"-typed Opportunities hanging off of a Contact.

The purpose is to enable us to use a Formula Field to let all SalesForce users know that Admissions is working with a Contact. Then Admissions doesn't have to manually click buttons saying so. They just have to do their day-to-day work.

@isTest private class TestCountAdmOppsForContact {
static testMethod void test() {
Account a = new account(Name='Fake Account');

insert a;

Contact c = new Contact(AccountId=a.id,LastName='Daikoku');

insert c;

Opportunity o1 = new Opportunity(AccountId=a.id,RecordTypeId='087C0000000KIVR',Name='Graduate Admissions 1',CloseDate=System.today(),StageName='Lead');

insert o1;

OpportunityContactRole ocr1 = new OpportunityContactRole(opportunityid=o1.id,contactid=c.id,IsPrimary=true);

insert ocr1;

Test.startTest();

delete o1;

Test.stopTest();

List expectedResult = [SELECT count_distinct(OpportunityId) gacount FROM OpportunityContactRole WHERE IsPrimary=true AND ContactID=:c.id AND OpportunityId in (SELECT Id FROM Opportunity WHERE RecordTypeId='087C0000000KIVR') GROUP BY ContactId];

Integer aoppcnt;

if(expectedResult.size() > 0) {
aoppcnt = (Integer)expectedResult[0].get('expr0');
} else {
aoppcnt = 0;
}

system.assertEquals(aoppcnt,c.Adm_Opp_Count__c,'Adm Opportunity Count did not populate correctly');
}
}

 

Next I'll work on writing an Apex Class with a method that populates Contact.Adm_Opp_Count__c with the value in my SOQL query (or null if it returns empty/0).

Then, I'll write an AFTER trigger for INSERT/UPDATE/DELETE on Opportunity to fire my method above.

Finally, I'll loop back around to beefing up my test class.

 

Oh...and then I guess I have to figure out this whole deployment thing if it works. But that's the champagne pop.

No comments:

Post a Comment