No Results
Search Tips:
- Please consider misspellings
- Try different search keywords
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");trigger 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}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");@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}