Newer Version Available

This content describes an older version of this product. View Latest

Example of an Uninstall Script

This sample uninstall script performs the following actions on package uninstall.
  • Inserts an entry in the feed describing which user did the uninstall and in which organization
  • Creates and sends an email message confirming the uninstall to that user
1global class UninstallClass implements UninstallHandler {
2  global void onUninstall(UninstallContext ctx) {
3    FeedItem feedPost = new FeedItem();
4    feedPost.parentId = ctx.uninstallerID();
5    feedPost.body = 'Thank you for using our application!';
6    insert feedPost;
7
8    User u = [Select Id, Email from User where Id =:ctx.uninstallerID()];   
9    String toAddress= u.Email;
10    String[] toAddresses = new String[] {toAddress};
11    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
12    mail.setToAddresses(toAddresses);
13    mail.setReplyTo('support@package.dev');
14    mail.setSenderDisplayName('My Package Support');
15    mail.setSubject('Package uninstall successful');
16    mail.setPlainTextBody('Thanks for uninstalling the package.');
17    Messaging.sendEmail(new Messaging.Email[] { mail });
18  }
19}

You can test an uninstall script using the testUninstall method of the Test class. This method takes as its argument a class that implements the UninstallHandler interface.

This sample shows how to test an uninstall script implemented in the UninstallClass Apex class.
1@isTest
2static void testUninstallScript() {
3  Id UninstallerId = UserInfo.getUserId();
4  List<FeedItem> feedPostsBefore = 
5    [SELECT Id FROM FeedItem WHERE parentId=:UninstallerId AND CreatedDate=TODAY];
6  Test.testUninstall(new UninstallClass());
7  List<FeedItem> feedPostsAfter = 
8    [SELECT Id FROM FeedItem WHERE parentId=:UninstallerId AND CreatedDate=TODAY];
9  System.assertEquals(feedPostsBefore.size() + 1, feedPostsAfter.size(), 
10    'Post to uninstaller failed.');
11}