Newer Version Available
Testing Behavior in Package Versions
When you change the behavior in an Apex class or trigger for different package versions, it is important to test that your code runs as expected in the different package versions. You can write test methods that change the package version context to a different package version by using the system method runAs. You can only use runAs in a test method.
The following sample shows a trigger with different behavior for different package versions.
1swfobject.registerObject("clippy.codeblock-0", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17trigger oppValidation on Opportunity (before insert, before update) {
18
19 for (Opportunity o : Trigger.new){
20
21 // Add a new validation to the package
22 // Applies to versions of the managed package greater than 1.0
23 if (System.requestVersion().compareTo(new Version(1,0)) > 0) {
24 if (o.Probability >= 50 && o.Description == null) {
25 o.addError('All deals over 50% require a description');
26 }
27 }
28
29 // Validation applies to all versions of the managed package.
30 if (o.IsWon == true && o.LeadSource == null) {
31 o.addError('A lead source must be provided for all Closed Won deals');
32 }
33 }
34}The following test class uses the runAs method to verify the trigger's behavior with and without a specific version:
1swfobject.registerObject("clippy.codeblock-1", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17@isTest
18private class OppTriggerTests{
19
20 static testMethod void testOppValidation(){
21
22 // Set up 50% opportunity with no description
23 Opportunity o = new Opportunity();
24 o.Name = 'Test Job';
25 o.Probability = 50;
26 o.StageName = 'Prospect';
27 o.CloseDate = System.today();
28
29 // Test running as latest package version
30 try{
31 insert o;
32 }
33 catch(System.DMLException e){
34 System.assert(
35 e.getMessage().contains(
36 'All deals over 50% require a description'),
37 e.getMessage());
38 }
39
40 // Run test as managed package version 1.0
41 System.runAs(new Version(1,0)){
42 try{
43 insert o;
44 }
45 catch(System.DMLException e){
46 System.assert(false, e.getMessage());
47 }
48 }
49
50 // Set up a closed won opportunity with no lead source
51 o = new Opportunity();
52 o.Name = 'Test Job';
53 o.Probability = 50;
54 o.StageName = 'Prospect';
55 o.CloseDate = System.today();
56 o.StageName = 'Closed Won';
57
58 // Test running as latest package version
59 try{
60 insert o;
61 }
62 catch(System.DMLException e){
63 System.assert(
64 e.getMessage().contains(
65 'A lead source must be provided for all Closed Won deals'),
66 e.getMessage());
67 }
68
69 // Run test as managed package version 1.0
70 System.runAs(new Version(1,0)){
71 try{
72 insert o;
73 }
74 catch(System.DMLException e){
75 System.assert(
76 e.getMessage().contains(
77 'A lead source must be provided for all Closed Won deals'),
78 e.getMessage());
79 }
80 }
81 }
82}