0

Can anyone help me to write a unit test for following trigger:

trigger deletionPrevention on Attachment (before delete)
{
private list<Profile> allowedProfiles = [ SELECT Id, Name FROM Profile WHERE Name IN ('System Administrator') ];
private list<User> allowedUsers = [ SELECT Id, ProfileId FROM User WHERE ProfileId IN :allowedProfiles ];
private User theUser = new User(Id = system.Userinfo.getUserId(), ProfileId = system.Userinfo.getProfileId());

for ( Attachment currAtt : trigger.old ){
 if ( !( isAllowed(currAtt, theUser, allowedUsers) ) ){
   currAtt.CreatedById.addError('\nYou don\'t have the rights to delete this attachment.\n'
   + 'For further information contact your System Administrator.\n');
 }
}
private static boolean isAllowed(Attachment att, User aUser, list<User> allowedUsersList){
 boolean isAllowed = false;
 for ( User currUser : allowedUsersList ){
  if ( aUser.Id == currUser.Id ){
   isAllowed = true;
  }
}
return isAllowed;
}
}
3
  • 3
    What have you tried so far? Where are you stuck? The format here is not intended to be to just ask people to do your work for you.
    – Adrian Larson
    Commented Jan 24, 2017 at 6:19
  • How do i make a current user in the unittest? Commented Jan 24, 2017 at 6:22
  • @Eager2Learnapex Did the code below help you?
    – Richard N
    Commented Jan 29, 2017 at 6:26

3 Answers 3

0

Add the below code in your test class.

@isTest
Private class DeletionPreventionTest{

     @isTest static void testDeletionPrevention(){
            //Insert Account
            Account acc = new Account();
            acc.Name = 'Test Account';
            insert acc;

            //Insert attachment
            Attachment att = new Attachment();
            att.ParentId = parentId;
            att.Name = 'Test Attachment for Parent';
            att.Body = Blob.valueOf('Test Data');;
            insert att;

            User thisUser = new User();
            thisUser.Id = Userinfo.getuserId();
            thisUser.ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1][0].Id;

            System.runAs ( thisUser ) {
               delete att;
            }
        }
    }

Few suggestion with your code.

  1. Avoid unwanted SOQL queries and variables. It will affect your code performance.
0

You can get the current user id like this.

UserInfo.getUserId()

which returns the user id of the current user.

For example :

User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];

    System.runAs ( thisUser ) {
        UserRole ur = [Select PortalType, PortalAccountId From UserRole where PortalType =:'CustomerPortal' limit 1];
        Profile p = [select Id,name from Profile where UserType in :customerUserTypes limit 1];
    }

Let me know if this will helps

0

As Adrian said, you would need to put some effort towards your question and actually tell us what you have done and what you need help with.

But seeing that you are new and the fact that your handle could suggest your enthusiasm towards learning APEX :), I have gone ahead and written a little test code for you.

This should help you with regards to the unit test and you should complete the To-Do sections. In a nutshell, your APEX unit test code must:

    1. Provide code coverage (Salesforce requires 75% but you should strive for 100%).
    2. Test whether your code works as intended (Positive/Negative conditions, testing profile access etc).
@isTest
public class TestDeleteAttachment {

    @testSetup static void prepData()
    {
        Profile p1 = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];       
        User testUser = new User(FirstName = 'Test', LastName = 'User', ProfileId = p1.Id,Email = '[email protected]', userName='[email protected]',alias='utest',
                                timezonesidkey='America/Chicago',localesidkey='en_US',emailencodingkey='UTF-8',languagelocalekey='en_US');
        insert testUser;

        //TO-DO: Create another user with a different profile in your org

        //Create a dummy record
        Account a1 = New Account (Name='ACME');
        insert a1;
        //Create Attachment
        Attachment attach = New Attachment();
        attach.Name = 'Test Attachment';       
        Blob bodyBlob=Blob.valueOf('Dummy Body');
        attach.body=bodyBlob;
        attach.parentId=a1.id;
        insert attach;

    }
    static testMethod void testDeleteAttach1()
    {

        //First fetch the user you created in test setup
        User u = [select Id from User where Username = '[email protected]'];
        Attachment attach = [Select Id from Attachment where Name = 'Test Attachment' LIMIT 1];

        System.runas(u)
        {
            //Delete the attachment to test the trigger
            Test.startTest();
            delete attach;
            Test.stopTest(); 
        }
    }
    static testMethod void testDeleteAttach2()
    {

        //To-DO: Use the 2nd user to test whether your trigger prevents the deletion as expected
        //Also add methods to test the method 'isAllowed'
    }

}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .