I'm very new to APEX and I'm trying to implement a feature where new contacts added contain a field called Company__c. From this field, a lookup is done to find the Account by the same name, and then associates the two.
My code is as follows:
trigger associateWithAccount on Contact (before insert) {
if(Trigger.isBefore){
if(Trigger.isInsert){
Map<String, String> extMap = new Map<String, String>();
Set<String> extIdSet = new Set<String>();
for(Contact c : Trigger.new){
extIdSet.add(c.Company__c);
}
for(Account a : [select Id, Name from Account where Name IN :extIdSet]){
extMap.put(a.Id, a.Name);
}
for(Contact c : Trigger.new){
c.AccountID = extMap.get(c.Company__c);
}
}
}
}
I have no idea if that works, I just know it doesn't give me any errors. However, I have no idea how to write the test class to attain the necessary code coverage, nor how to link the trigger and the test class. Any help?
This is my test code so far, but I keep getting an error about the Account__r (which I've never used before):
@isTest
private class TestAssociateWithAccount {
static testMethod void myUnitTest() {
Account testAccount = new Account(AccountID='98765', Account='test123');
insert testAccount;
Test.startTest();
Contact testContact = new Contact(Company__c='test123');
insert testContact;
Test.stopTest();
Contact result = [select AccountID, Account__r.Name, Account__r.Account from Contact where Company__c = 'test123' limit 1];
system.assertEquals(testAccount.AccountID, result.Contact__c);
}
}
Thanks!
Edit: Current Trigger Code:
trigger associateWithAccount on Contact (before insert) {
Map<String, String> extMap = new Map<String, String>();
for(Contact c : Trigger.new){
extMap.put(c.Company__c,null);
}
for(Account a : [select Id, Name from Account where Name IN :extMap.keySet()]){
extMap.put(a.Name,a.ID);
}
for(Contact c : Trigger.new){
ID tmp = extMap.get(c.Company__c);
if(tmp != null)
c.AccountID = tmp;
}
}
Current Test Class Code:
@isTest
private class TestAssociateWithAccount {
static testMethod void myUnitTest() {
Account testAccount = new Account(ID='5003000000D8cuI', Name='test123');
insert testAccount;
Test.startTest();
Contact testContact = new Contact(Company__c='test123');
insert testContact;
Test.stopTest();
Contact result = [select AccountID, Account.Name from Contact where Company__c = 'test123' limit 1];
system.assertEquals(testAccount.ID, result.AccountID);
}
}
ID='5003000000D8cuI',
From the Account you are creating. The ID will be populated when it is inserted