1
trigger deletecontact on Contact (before delete) {
    string uid=userinfo.getuserId();
    for(contact c: trigger.old)
    If(c.CreatedById != uid )         
    { 
        c.addError('This contact cannot be Deleted. please contact the Administration Department. Thank you.');           
    }  
}

i am not getting the code coverage for this trigger, this is my Test Class:

@istest(seealldata=true)
public class deletecontact1{
    static testmethod void unittest(){
        string uid=userinfo.getuserId();

        contact c=new contact();
        if(c.CreatedById!=uid){
           c.id='003N0000004yF8l';
           delete c;
        }
    }
}
3

To test your trigger effectively, you need to basically re-create what is going to happen when a user deletes a Contact. Once you have done that, you should really test that the outcome is correct by 'asserting' that it is in your test code.

There are a couple of problems with your test class as it stands. Firstly, you cannot delete something that hasn't yet been inserted and secondly you are referring to org specific data by including the ID. You should:

  1. Create and Insert a new Contact in your test class (as one user, using System.runAs)
  2. Delete the Contact (as another user, again using System.runAs)
  3. Catch the Error and assert that the message is correct (using System.assertEquals)

That would be the right thing to do, alternatively you could break all the rules of best practice and simply try to achieve coverage this way:

try { 
   delete [ select Id From Contact Where Id = '003N0000004yF8l'];
} catch (Exception e)
{
   // do nothing
}

However, this approach is not advisable because a) it is specifying an ID in the test class, this won't exist in your Production org when you try to deploy the trigger there it will actually fail, and b) the test does not actually 'test' the scenario you are coding for.

There is really no shortcut for proper testing, you should do some research, this is a good resource and illustrates most of what I have just discussed:

http://wiki.developerforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

EDIT: An example of such a test might be:

@istest
public class deletecontact1{
    static testmethod void unittest(){

        contact c=new contact();
        c.lastname='greg';
        insert c;

        System.runAs([select Id From User Where Username='anotheruser@org.com']){
            try{
                delete c;
            }catch(Exception e) {
                system.assert(e.getMessage().contains('This contact cannot be Deleted. please contact the Administration Department. Thank you.'));
            }
        }
    }
}

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.