インストール後スクリプトの例
次のインストール後スクリプトのサンプルは、パッケージのインストール/アップグレード時に次のアクションを実行します。
-
以前のバージョンが null である場合、つまりパッケージが初めてインストールされている場合、スクリプトは次を行う
- 「Newco」という新しいアカウントを作成し、作成されたことを検証する。
- 「Client Satisfaction Survey」というカスタムオブジェクト Survey の新しいインスタンスを作成する。
- 登録者に、パッケージのインストールを確認するメールメッセージを送信する。
- 以前のバージョンが 1.0 である場合、「Upgrading from Version 1.0」という Survey の新しいインスタンスを作成する。
- パッケージがアップグレードである場合、「Sample Survey during Upgrade」という Survey の新しいインスタンスを作成する。
- アップグレードがプッシュで実行されている場合、「Sample Survey during Push」という Survey の新しいインスタンスを作成する。
1global class PostInstallClass implements InstallHandler {
2 global void onInstall(InstallContext context) {
3 if(context.previousVersion() == null) {
4 Account a = new Account(name='Newco');
5 insert(a);
6
7 Survey__c obj = new Survey__c(name='Client Satisfaction Survey');
8 insert obj;
9
10 User u = [Select Id, Email from User where Id =:context.installerID()];
11 String toAddress= u.Email;
12 String[] toAddresses = new String[]{toAddress};
13 Messaging.SingleEmailMessage mail =
14 new Messaging.SingleEmailMessage();
15 mail.setToAddresses(toAddresses);
16 mail.setReplyTo('support@package.dev');
17 mail.setSenderDisplayName('My Package Support');
18 mail.setSubject('Package install successful');
19 mail.setPlainTextBody('Thanks for installing the package.');
20 Messaging.sendEmail(new Messaging.Email[] { mail });
21 }
22 else
23 if(context.previousVersion().compareTo(new Version(1,0)) == 0) {
24 Survey__c obj = new Survey__c(name='Upgrading from Version 1.0');
25 insert(obj);
26 }
27 if(context.isUpgrade()) {
28 Survey__c obj = new Survey__c(name='Sample Survey during Upgrade');
29 insert obj;
30 }
31 if(context.isPush()) {
32 Survey__c obj = new Survey__c(name='Sample Survey during Push');
33 insert obj;
34 }
35 }
36 }
インストール後スクリプトは、Test クラスの新しい testInstall メソッドを使ってテストできます。このメソッドが取る引数は、次のとおりです。
- InstallHandler インターフェースを実装するクラス。
- 既存のパッケージのバージョン番号を指定する Version オブジェクト。
- インストールがプッシュである場合は true である省略可能な Boolean 値。デフォルトは、false です。
このサンプルでは、PostInstallClass Apex クラスに実装されたインストール後スクリプトのテスト方法を説明しています。
1@isTest
2static void testInstallScript() {
3 PostInstallClass postinstall = new PostInstallClass();
4 Test.testInstall(postinstall, null);
5 Test.testInstall(postinstall, new Version(1,0), true);
6 List<Account> a = [Select id, name from Account where name ='Newco'];
7 System.assertEquals(a.size(), 1, 'Account not found');
8 }