パッケージバージョンの動作のテスト
異なるパッケージバージョ��の Apex クラスまたはトリガーの動作を変更する場合、異なるパッケージバージョンでコードが期待通り実行されるようにテストすることが重要です。システムメソッド runAs を使用して、パッケージバージョンコンテキストを異なるパッケージバージョンに変更するテストメソッドを記述できます。テストメソッドでは runAs のみ使用できます。
次の例は、異なるパッケージバージョンのトリガーのさまざまな動作を示しています。
1trigger oppValidation on Opportunity (before insert, before update) {
2
3 for (Opportunity o : Trigger.new){
4
5 // Add a new validation to the package
6 // Applies to versions of the managed package greater than 1.0
7 if (System.requestVersion().compareTo(new Version(1,0)) > 0) {
8 if (o.Probability >= 50 && o.Description == null) {
9 o.addError('All deals over 50% require a description');
10 }
11 }
12
13 // Validation applies to all versions of the managed package.
14 if (o.IsWon == true && o.LeadSource == null) {
15 o.addError('A lead source must be provided for all Closed Won deals');
16 }
17 }
18}次のテストクラスでは、runAs メソッドを使用して、特定のバージョンの有無におけるトリガーの動作を検証します。
1@isTest
2private class OppTriggerTests{
3
4 static testMethod void testOppValidation(){
5
6 // Set up 50% opportunity with no description
7 Opportunity o = new Opportunity();
8 o.Name = 'Test Job';
9 o.Probability = 50;
10 o.StageName = 'Prospect';
11 o.CloseDate = System.today();
12
13 // Test running as latest package version
14 try{
15 insert o;
16 }
17 catch(System.DMLException e){
18 System.assert(
19 e.getMessage().contains(
20 'All deals over 50% require a description'),
21 e.getMessage());
22 }
23
24 // Run test as managed package version 1.0
25 System.runAs(new Version(1,0)){
26 try{
27 insert o;
28 }
29 catch(System.DMLException e){
30 System.assert(false, e.getMessage());
31 }
32 }
33
34 // Set up a closed won opportunity with no lead source
35 o = new Opportunity();
36 o.Name = 'Test Job';
37 o.Probability = 50;
38 o.StageName = 'Prospect';
39 o.CloseDate = System.today();
40 o.StageName = 'Closed Won';
41
42 // Test running as latest package version
43 try{
44 insert o;
45 }
46 catch(System.DMLException e){
47 System.assert(
48 e.getMessage().contains(
49 'A lead source must be provided for all Closed Won deals'),
50 e.getMessage());
51 }
52
53 // Run test as managed package version 1.0
54 System.runAs(new Version(1,0)){
55 try{
56 insert o;
57 }
58 catch(System.DMLException e){
59 System.assert(
60 e.getMessage().contains(
61 'A lead source must be provided for all Closed Won deals'),
62 e.getMessage());
63 }
64 }
65 }
66}