2

I currently have a trigger that is meant to make the owner of a contact the same as the owner for the account.

The trigger itself works without issue but uploading it puts my org at 73% code coverage.

I figured it should be easy to have code coverage on this trigger as it is a simple one.

The test however doesn't seem to provide any coverage at all on any class.

How can I get this code covered?

Trigger:

trigger ChangeOwnerToAccountOwner on Contact (before insert) {
    List<Contact> contacts = new List<Contact>();
    for(Contact c:trigger.new){
        contacts.add(c);
    } 
    Account account = [SELECT Id, OwnerId FROM Account WHERE Id = :contacts[0].AccountId];
    for(Contact c:contacts){
        c.OwnerId = account.OwnerId;
    }
}

Test Class:

@isTest
public class ChangeOwnerToAccountOwnerTest {
   public static Contact testContact;
   public static Account testAccount;
   public static User testUser;

    static void init(){
        testContact = new Contact(lastName = 'Test', firstName = 'Contact');
        testAccount = new Account(Name = 'Test Account 001');
        Profile p = [select id from profile where name='Standard User'];
        testUser = new User(alias = 'standt', email='standarduser@testorg.com',
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
            localesidkey='en_US', profileid = p.Id,
            timezonesidkey='America/Los_Angeles', username='standarduser001@testorg.com');

    }

    static testMethod void testNewContactAdded() {
        init();
        test.startTest();

        insert testUser;
        testAccount.OwnerId = testUser.Id;
        insert testAccount;
        testContact.AccountId = testAccount.Id;
        insert testContact;

        Contact testContactQuery = [SELECT Id, OwnerId FROM Contact WHERE Id = :testContact.Id LIMIT 1];
        System.assertEquals(testAccount.OwnerId, testContactQuery.OwnerId);

        test.stopTest();
    }
}
  • it would be great if you can update your question with screenshot of code coverage so that we can tell you what you are missing. – Himanshu Nov 3 '15 at 19:21
  • Are you sure the trigger has no coverage? There's a bit of a bug in how developer console shows test coverage sometimes, I've had a hard time tracking it down. Go to Setup -> Develop -> Apex Test Execution and run the test from there. Then go to Setup -> Develop -> Apex Triggers and click on the name of your trigger to see it's code coverage. Based on your test, it should be covered, so I'd expect a high percentage there, and somewhere else you need more coverage. – Christian Carter Nov 3 '15 at 19:25
  • @ChristianCarter you were totally right! And sfdcfox's fix actually fixed the other things that were failing due to the change. – Cody Beaner Nov 4 '15 at 16:22
5

You have a bug in your code: if the account owners are different (in a batch of inserts), all contacts will be assigned to the same account owner. Also, your code will crash if the contact has no account ("query has no rows for assignment"). Instead, you should do this:

trigger AssignOwner on Contact (before insert) {
    Map<Id, Account> accounts = new Map<Id, Account>();
    for(Contact record: Trigger.new) {
        accounts.put(record.AccountId, null);
    }
    accounts.remove(null);
    accounts.putAll([SELECT OwnerId FROM Account WHERE Id IN :accounts.keySet()]);
    for(Contact record: Trigger.new) {
        if(record.AccountId != null) {
            record.OwnerId = accounts.get(record.AccountId).OwnerId;
        }
    }
}

As for why it's not passing? Most likely, you have a validation rule in your account or contacts that's preventing your test from reaching the trigger. You'll need to check your test logs to find out why it's failing. This also explains why your coverage is only 73%-- a change in production has caused several unit tests to fail.

Edit:

One final suggestion: Set up your test to prove that all scenarios work. I'd probably suggest creating users U1, U2, and U3, then create two accounts A1 (Owner = U2) and A2 (Owner = U3), then create three contacts C1 (Owner = U1, Account = A1), C2 (Owner = U2, Account = A2), and C3 (Owner = U1, Account = null). How this all plays out is that C1 should be owned by U2, C2 should be owned by U3, and C3 should be owned by U1.

| improve this answer | |
  • There was no validation rule, or workflow rule on our accounts or contacts, and using your trigger actually caused the other errors from unrelated tests to cease to succeed. – Cody Beaner Nov 4 '15 at 16:24
  • 1
    @CodyBeaner I'm glad I was able to help you out with this. I hope you'll study this code a bit, it's one of the most common design patterns you'll use for writing triggers. – sfdcfox Nov 4 '15 at 17:04
  • I think mainly I will just need to learn more about Maps, and how to use them effectively. – Cody Beaner Nov 5 '15 at 15:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.