• Kasia Wojewodzka 7
  • NEWBIE
  • 60 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 12
    Questions
  • 9
    Replies
Hi, I am new to test class. Would anyone help with the Too many SOQL queries 101 test clsss error ?  I am getting the Too many SOQL queries in each method where I quary the user.  Thank you for looking at it. 
@isTest
public class Test_VR_WFMRestrictStatusCxlToSup {
    
    @TestSetup
    static void createTestData(){
        User fsrUser = [Select Id,UserRole.Name,Name,Profile.Name,Username From User 
                        Where UserRole.Name = 'FSR-DX Mid Atlantic' 
                        AND Profile.Name = 'Field Support Rep - CAG'
                        AND Reporting_Role__c = 'FSR DX'
                        AND isActive = true LIMIT 1];    
         User fsrUserFSRDR = [Select Id,UserRole.Name,Name,Profile.Name,Username From User 
                        Where UserRole.Name = 'FSR-DR West' 
                        AND Profile.Name = 'Field Support Rep - CAG'
                        AND Reporting_Role__c = 'FSR DR'
                        AND isActive = true LIMIT 1];                
        
        Account placeHolderAcc1 = new ACCOUNT();
        Account placeHolderAcc2 = new ACCOUNT();
        Account placeHolderAcc3 = new ACCOUNT();
        Account placeHolderAcc4 = new ACCOUNT();
        
        System.runAs(fsrUser) {
            placeHolderAcc1 = new Account(Name='Test Account WFM VR1', SAP_Customer_Number__c ='1111198700', ShippingCountryCode='US', ShippingState='Maine',
                                        BillingCountryCode='US',BillingStreet='1 ', BillingCity='Pord',BillingState='Maine', 
                                        BillingPostalCode='04092',TIN__c='111111111');
            insert placeHolderAcc1;
            
            placeHolderAcc2 = new Account(Name='Test Account WFM VR2', SAP_Customer_Number__c ='1111198701', ShippingCountryCode='US', ShippingState='Maine',
                                        BillingCountryCode='US',BillingStreet='1 street', BillingCity='Wes',BillingState='Mai', 
                                        BillingPostalCode='04092',TIN__c='111111112');
            insert placeHolderAcc2;
            
            placeHolderAcc3 = new Account(Name='Test Account WFM VR3', SAP_Customer_Number__c ='1111198702', ShippingCountryCode='US', ShippingState='Maine',
                                        BillingCountryCode='US',BillingStreet='1 street', BillingCity='West',BillingState='Mae', 
                                        BillingPostalCode='04092',TIN__c='111111113');
            insert placeHolderAcc3;
  }         
    
    System.runAs(fsrUserFSRDR) {
            placeHolderAcc4 = new Account(Name='Test Account WFM VR4', SAP_Customer_Number__c ='1111198704', ShippingCountryCode='US', ShippingState='Maine',
                                        BillingCountryCode='US',BillingStreet='1 streeet', BillingCity='We',BillingState='ME', 
                                        BillingPostalCode='04092',TIN__c='111111111');
            insert placeHolderAcc4;
    
    
     }    
      
       RecordType woProactive4 = [SELECT Id,Name,SobjectType FROM RecordType WHERE SobjectType = 'WorkOrder' and Name = 'Proactive' Limit 1];
        System.runAs(fsrUserFSRDR) {
            WorkOrder createWorkOrder4 = new WorkOrder(AccountId = placeHolderAcc4.Id, Status = 'New', RecordTypeId = woProactive4.Id);
            insert createWorkOrder4;
    
   }    
        
        RecordType woProactive = [SELECT Id,Name,SobjectType FROM RecordType WHERE SobjectType = 'WorkOrder' and Name = 'Proactive' Limit 1];
        System.runAs(fsrUser) {
            WorkOrder createWorkOrder1 = new WorkOrder(AccountId = placeHolderAcc1.Id, Status = 'New', RecordTypeId = woProactive.Id);
            insert createWorkOrder1;
            WorkOrder createWorkOrder2 = new WorkOrder(AccountId = placeHolderAcc2.Id, Status = 'New', RecordTypeId = woProactive.Id);
            insert createWorkOrder2;
            WorkOrder createWorkOrder3 = new WorkOrder(AccountId = placeHolderAcc3.Id, Status = 'New', RecordTypeId = woProactive.Id);
            insert createWorkOrder3;
        
        }
    }
    
    // Testing that non-direct supervisor, supervisor can cancel work order
    @IsTest(SeeAllData = false)
    static void testSupervisorCanCancelWO() {
        User fsrSupUser = [Select Id,UserRole.Name,Name,Profile.Name,Username From User 
                           Where UserRole.Name = 'FSR-DX Supervisor North Central' 
                           AND Profile.Name = 'Field Support Rep - CAG'
                           AND Reporting_Role__c = 'FSR DX Supervisor'
                           AND isActive = true LIMIT 1];
        
        system.debug('Supervisor User: ' + fsrSupUser.Name);
        
        WorkOrder w = [Select id From WorkOrder WHERE Account.Name = 'Test Account WFM VR1'];
        w.status = 'Canceled';
        w.Cancellation_Reason__c = 'Duplicate';
        w.Cancellation_Notes__c = 'Some notes';
        Test.startTest();
        System.runAs(fsrSupUser) {
            Update w;
        }
        Test.stopTest();
        
        w = [Select id, status, Cancellation_Reason__c From WorkOrder WHERE Account.Name = 'Test Account WFM VR1'];
        System.assertEquals('Canceled', w.Status);
        
    }
    
    // testing that owner of work order can cancel work order
    @IsTest(SeeAllData = false)
    static void testOwnerCanCancelWO() {
        User fsrUser = [Select Id,UserRole.Name,Name,Profile.Name,Username From User 
                        Where UserRole.Name = 'FSR-DX Mid Atlantic' 
                        AND Profile.Name = 'Field Support Rep - CAG'
                        AND Reporting_Role__c = 'FSR DX'
                        AND isActive = true LIMIT 1];
        
        system.debug('fsr User: ' + fsrUser.Name);
        
        WorkOrder w = [Select id From WorkOrder WHERE Account.Name = 'Test Account WFM VR2'];
        w.status = 'Canceled';
        w.Cancellation_Reason__c = 'Duplicate';
        w.Cancellation_Notes__c = 'Some notes';
        Test.startTest();
        System.runAs(fsrUser) {
            Update w;
        }
        Test.stopTest();
        
        w = [Select id, status, Cancellation_Reason__c From WorkOrder WHERE Account.Name = 'Test Account WFM VR2'];
        System.assertEquals('Canceled', w.Status);
        
    }
    
    // testing that owner of work order can cancel work order US78297 Added new Reporting role FSR DR that can cancel the order
    @IsTest(SeeAllData = false)
    static void testOwnerCanCancelWOFSRDR() {
        User fsrUserFSRDR = [Select Id,UserRole.Name,Name,Profile.Name,Username From User 
                        Where UserRole.Name = 'FSR-DR West' 
                        AND Profile.Name = 'Field Support Rep - CAG'
                        AND Reporting_Role__c = 'FSR DR'
                        AND isActive = true LIMIT 1];
        
        system.debug('fsrUserFSRDR User: ' + fsrUserFSRDR.Name);
        
        WorkOrder w = [Select id From WorkOrder WHERE Account.Name = 'Test Account WFM VR4'];
        w.status = 'Canceled';
        w.Cancellation_Reason__c = 'Duplicate';
        w.Cancellation_Notes__c = 'Some notes';
        Test.startTest();
        System.runAs(fsrUserFSRDR) {
            Update w;
        }
        Test.stopTest();
        
        w = [Select id, status, Cancellation_Reason__c From WorkOrder WHERE Account.Name = 'Test Account WFM VR4'];
        System.assertEquals('Canceled', w.Status);
        
    }
    
    // Test that non owner, non supervisor can't cancel work order
    @IsTest(SeeAllData = false)
    static void testNonOwnerNonSupCantCancelWO() {
        WorkOrder w = [SELECT Id, OwnerId FROM WorkOrder WHERE Account.Name = 'Test Account WFM VR3'];
        User fsrUser = [SELECT Id, UserRole.Name, Name, Profile.Name, Username FROM User 
                        WHERE UserRole.Name = 'FSR-DX Mid Atlantic' 
                        AND Profile.Name = 'Field Support Rep - CAG'
                        AND Reporting_Role__c = 'FSR DX'
                        AND Id != :w.OwnerId 
                        AND isActive = true LIMIT 1];
        w.status = 'Canceled';
        w.Cancellation_Reason__c = 'Duplicate';
        w.Cancellation_Notes__c = 'Some notes';
        Test.startTest();
        try {
            System.runAs(fsrUser) {
                Update w;
            }
        } catch(DMLException de) {
            System.debug('Error: ' + de.getMessage());
        }
        
        Test.stopTest();
        
        w = [Select id, status, Cancellation_Reason__c From WorkOrder WHERE Account.Name = 'Test Account WFM VR3'];
        System.assertNotEquals('Canceled', w.Status);
        
    }
}
Hello 
Hoping that you can help me!
I would like to modify this Validation rule to use for example Case Record Type Name or  Case Record Type Developer Name instead of hardcoded Ids.  

When I tried to replace RecordTypeId = '0123Z000000LKZa' with RecordType.Name I received the error:
PRIORVALUE function cannot reference the RecordType.Name field.

Here is my validation rule: 

AND
(
RecordTypeId = '0123Z000000LKZb',
ISCHANGED(RecordTypeId),
PRIORVALUE(RecordTypeId) = '0123Z000000LKZa',
$Profile.Name <> "System Administrator",
$Profile.Name <> "System Integration",
$Profile.Name <> "CRM Team"

)
Hi I am trying to mass update Knowledge Articles from Published to Drafts  (Developer Console: Debug> Execute Anonymos Windwow) 
Its been working succesfully with smaller updates until when I got about 1600 articles to update.
List<Knowledge__kav> articleIds = [SELECT Id,Region__c,LastPublishedDate,Line_of_business__c,Title, KnowledgeArticleId FROM Knowledge__kav WHERE PublishStatus = 'Online' AND Title <> 'Digital Cytology: Slide Scanning' AND Title <> 'SNAP Tests: Universal SNAP Protocol Checklist' AND Title <> 'SNAPShot Dx: Streaking and/or Speckling' AND Title <> 'This is a test of LOB and Region' AND Title <> 'SNAPShot Dx: Streaking and/or Speckling' AND Title <> 'Cornerstone: Lab results run under the wrong patient - wrong patient on lab report PDF' AND  Line_of_business__c ='' AND  Language = 'en_US' WITH DATA CATEGORY Line_of_Business__c AT (IHD__c) LIMIT 100];
for(Knowledge__kav article : articleIds){
KBManagement.PublishingService.editOnlineArticle(article.KnowledgeArticleId, true);
}
system.Debug(articleIds.size());



I am getting the follwoing error. 

System.HandledException: You can't perform this action. Be sure the action is valid for the current state of the article, and that you have permission to perform it.

I think we may be running into "one or more of those online article already has a draft article" issue mentioned here: https://salesforce.stackexchange.com/questions/115592/mass-updating-published-articles

I am new to apex code.  Would you advise how to modify the exsiting code i have to use Try and Catch ? Thank you in advance for your help. 

Kasia 

 
Dear Community 

Hope you can assit me with the error message I am getting when running test on the line 54?  

Knowledge__kav testArticle = [SELECT ID, Region__c, Line_of_Business__c FROM Knowledge__kav WHERE Title = 'TestIHDNA'];

Would you advise how to proceed?  
I am testing  Knowledge Article field updates here
1. If the knowloedge creator has certain  profile, I want to check if Knowdlege Article 2 custom fields were updated. 

2. Then if the knowledge article creator has a one of the roles listed, the fields on the Article are being updated per requirments. 


Best
Kasia 
 
@isTest
public class Test_PB_KnowledgeLOBnadRegionUpdates {


    //Tests the node "testVSSNA"
    @isTest
    static void testVSSNA(){
        Test.startTest();
        Profile p = [select id from Profile where profile.name='Customer and Technical Support - CAG NA'];
        User userVSSNA = [SELECT Id from User where ProfileId = :p.id AND IsActive = TRUE limit 1];
        System.runAs(userVSSNA){
            //Create a General Article
            Knowledge__kav testKnowledgeArticle = new Knowledge__kav(
                     RecordTypeId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('General').getRecordTypeId(),
                     Title = 'TestVSSNA',
                     UrlName = 'salesforce-crm',
                     Summary = 'Salesforce Cloud CRM',
                     Language = 'en_US'

              );
              insert testKnowledgeArticle;

                // Test if Region is North America and Line of Business is VSS
                Knowledge__kav testArticle =  [SELECT ID, Region__c, Line_of_Business__c FROM Knowledge__kav WHERE Title = 'TestVSSNA'];

                System.assertEquals(testArticle.Region__c, 'North America');
                System.assertEquals(testArticle.Line_of_Business__c, 'VSS');

            Test.stopTest();
        }
    }

    @isTest
    static void testIHDNA(){
        Test.startTest();
        Profile p = [select id from Profile where profile.name='Diagnostic Technical Support'];
        UserRole r = [SELECT Id FROM UserRole WHERE Name = 'CAG IHD CS Manager' or Name = 'CAG IHD CS Supervisor' or Name = 'CAG IHD CS Agent' LIMIT 1]; 
        // Create test user with specific role
        User userIHDNA = new User(UserRoleId = r.Id, ProfileId = p.Id, UserPermissionsKnowledgeUser = true, UserName='xxx@testorg.com', Alias = 'standt',Email='xxx@testorg.com',
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', TimeZoneSidKey='America/Los_Angeles');
        insert userIHDNA ;
        System.runAs(userIHDNA){
                //Create a General Article
                Knowledge__kav testKnowledgeArticle = new Knowledge__kav(
                RecordTypeId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('General').getRecordTypeId(),
                Title = 'TestIHDNA',
                UrlName = 'salesforce-crm',
                Summary = 'Salesforce Cloud CRM',
                Language = 'en_US'
                );
                insert testKnowledgeArticle;

                 // Test if Region is North America and Line of Business is VSS
                Knowledge__kav testArticle = [SELECT ID, Region__c, Line_of_Business__c FROM Knowledge__kav WHERE Title = 'TestIHDNA'];

                System.assertEquals(testArticle.Region__c, 'North America');
                System.assertEquals(testArticle.Line_of_Business__c, 'IHD');
                Test.stopTest();
         }
    }
}


 
Dear community

I am writting the test cass for Knoweldge Article.  
In the test class i am trying to instert Knowledge  article and test if the 2 custom field are being auto popualted.

If user who creates an article  has a certian profile, 2 custom fields on Knowledge articles l will be automaticlly populated: Region (North America)  and Line of busines (VSS).
 
@isTest
public class Test_PB_KnowledgeLOBnadRegionUpdates {
    //Tests the node "testVSSNA"
    @isTest
    static void testVSSNA(){
        Test.startTest();
        Profile p = [select id from Profile where profile.name='Customer and Technical Support - CAG NA'];
        User userVSSNA = [SELECT Id from User where ProfileId = :p.id AND IsActive = TRUE limit 1];
        System.runAs(userVSSNA){
          //Create a General Article
          Knowledge__kav testKnowledgeArticle = new Knowledge__kav(
                 RecordTypeId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('General').getRecordTypeId(),
                 Title = 'TestVSSNA',
                 UrlName = 'salesforce-crm',
                 Summary = 'Salesforce Cloud CRM',
                 Language = 'en_US'
              
          );
          insert testKnowledgeArticle;

            // Test if Region is North America and Line of Business is VSS
           Knowledge__kav testArticle =  [SELECT Id,Line_of_Business_c, Region_c FROM KnowledgeArticle WHERE Title = 'TestVSSNA'];
        
            System.assertEquals(testArticle.Line_of_Business_c, 'VSS');
            system.assertEquals(testArticle.Region_c, 'North America');
        Test.stopTest();        
    } 
  }
}
I am getting 3 errors: see screeshot below.  Would  you be able to assit how i can resolve the issues?  thank you in advance. 

best Kasia

User-added image
Dear Community  

I am buiding the test class for Validation rule that block users with Permission Set assigned and proper record type from editing certaint  fields. 

I keep running into the issue.  
Error Message   System.AssertException: Assertion Failed: Validation rule should throw correct error.: Expected: true, Actual: false
Stack Trace              Class.Test_VR_FSRNAAssetBlockEdit.Test_FSRNABlockPIMSEdit: line 215, column 1

Where I testing update of the Account ID.  
Line 215 is failing
System.assertEquals(true, validError, 'Validation rule should throw correct error.');

Any advise on how to fix the error would be much appriciated? 
Thnak you in advance. 
Kasia 
@isTest
public class Test_VR_FSRNAAssetBlockEdit {
    
    
    private class TestException extends Exception {}

    static final string PERM_SET = 'FSR_NA_DBR_Setup_and_Installation_Permissions';
    
    
    @testSetup
    public static void dataSetup() {
      // create test user with Field Support Rep NA profile 
    Profile FSRNA = [SELECT Id, Name FROM Profile WHERE Name = 'Field Support Rep - CAG'];
        

        User u = new User(
            Alias = 'CTSvTest',
            Email = 'TestAssetValidationRuleFSRNA@XXXX.com',
            Username = 'TestAssetValidationRS@XXXX.com',
            FirstName = 'CTS Test',
            LastName = 'UserAssetVR',
            TimeZoneSidKey = 'America/New_York',
            LocaleSidKey = 'en_US',
            EmailEncodingKey = 'UTF-8',
            LanguageLocaleKey = 'en_US',
            ProfileId = FSRNA.Id
        );

        insert u;
        
        // need to assign user to permission set
        PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = :PERM_SET];
    
        PermissionSetAssignment psa = new PermissionSetAssignment(
        PermissionSetId = ps.Id,
        AssigneeId = u.Id
        );
        insert psa;
        
        // Make Account
        Account acc = new Account();
        acc.Name = 'TestAccount';
        acc.BillingCity ='Boston' ;
        acc.BillingCountry='United States';
        acc.BillingPostalCode='600075';
        acc.BillingState=' Massachusetts';
        acc.BillingStreet='water well street';
        acc.ShippingCity ='Boston' ;
        acc.ShippingCountry='United States';
        acc.ShippingPostalCode='600075';
        acc.ShippingState=' Massachusetts';
        acc.ShippingStreet='water well street'; 
        acc.TIN__c = '1';

        System.runAs(u) {
            insert acc;
        }
    }  
    @IsTest
    static void Test_FSRNABlockPIMSEdit () {
        // Get Record Type
        Id assetRecordTypeId = Schema.SObjectType.Asset.getRecordTypeInfosByDeveloperName().get('XXXX_Practice_Information_Mgmt').getRecordTypeId();
        User u = [ SELECT Id FROM User WHERE Username = 'TestAssetValidationRS@XXXX.com' LIMIT 1 ];
        Account acc = [ SELECT Id FROM Account WHERE Name = 'TestAccount' LIMIT 1 ];

        Asset product = new Asset();
        product.Status = 'Installed';
        product.Is_Active__c = true;
        product.SerialNumber = 'TA001';
        product.RecordTypeId = assetRecordTypeId;
        product.AccountId = acc.Id;
        product.Asset_Category__c = 'Practice Software';
        product.Activation_Key__c = '1234-5678-90';
        product.Name = 'Cornerstone';
        insert product;

        // Test edit of activation key
        try {
            System.runAs(u) {
                product.Name = 'Cornerstone';
                product.Activation_Key__c = '0912-5678-90';
                update product;
        }
            throw new TestException('Failed to throw correctly');
        } catch (Exception e) {
            String errorMessage = e.getMessage();
            Boolean validError = errorMessage.contains('You cannot edit XXXX Products and Services record.');
            System.assertEquals(true, validError, 'Validation rule should throw correct error.');
        }

        System.runAs(u){
            product.Activation_Key__c = '0912-5678-90';
        }

        // Test edit of PIMS installed sw version
        try {
            System.runAs(u) {
                product.Name = 'Cornerstone';
                product.PIMS_Installed_SW_Version__c = '8.5.01.2';
                update product;
        }
            throw new TestException('Failed to throw correctly');
        } catch (Exception e) {
            String errorMessage = e.getMessage();
            Boolean validError = errorMessage.contains('You cannot edit XXXX Products and Services record.');
            System.assertEquals(true, validError, 'Validation rule should throw correct error.');
        }

        System.runAs(u){
            product.PIMS_Installed_SW_Version__c = '8.5.01.3';
        }

        // Test edit of PIMS primary OS
        try {
            System.runAs(u) {
                product.Name = 'Cornerstone';
                product.PIMS_Primary_Operating_System__c = 'Macintosh';
                update product;
        }
            throw new TestException('Failed to throw correctly');
        } catch (Exception e) {
            String errorMessage = e.getMessage();
            Boolean validError = errorMessage.contains('You cannot edit XXXX Products and Services record.');
            System.assertEquals(true, validError, 'Validation rule should throw correct error.');
        }

        System.runAs(u){
            product.PIMS_Primary_Operating_System__c = 'Windows';
        }

        // Test edit of Service Level
        try {
            System.runAs(u) {
                product.Name = 'Cornerstone';
                product.PIMS_Service_Level__c = 'Gold';
                update product;
        }
            throw new TestException('Failed to throw correctly');
        } catch (Exception e) {
            String errorMessage = e.getMessage();
            Boolean validError = errorMessage.contains('You cannot edit XXXX Products and Services record.');
            System.assertEquals(true, validError, 'Validation rule should throw correct error.');
        }

        System.runAs(u){
            product.PIMS_Service_Level__c  = 'Silver';
        }

       
       // Test edit of XXXX Unique Key
        try {
            System.runAs(u) {
                product.Name = 'Cornerstone';
                product.SAP_Cust_No_Type_ID__c = '1';
                update product;
        }
            throw new TestException('Failed to throw correctly');
        } catch (Exception e) {
            String errorMessage = e.getMessage();
            Boolean validError = errorMessage.contains('You cannot edit XXXX Products and Services record.');
            System.assertEquals(true, validError, 'Validation rule should throw correct error.');
        }

        System.runAs(u){
            product.SAP_Cust_No_Type_ID__c  = '2';
        }
        
       // Test edit of Version
        try {
            System.runAs(u) {
                product.Name = 'Cornerstone';
                product.Version__c = '1';
                update product;
        }
            throw new TestException('Failed to throw correctly');
        } catch (Exception e) {
            String errorMessage = e.getMessage();
            Boolean validError = errorMessage.contains('You cannot edit XXXX Products and Services record.');
            System.assertEquals(true, validError, 'Validation rule should throw correct error.');
        }

        System.runAs(u){
            product.Version__c  = '2';
        }
        
        // Test edit of PIMS Poeple ID 
        try {
            System.runAs(u) {
                product.Name = 'Cornerstone';
                product.PIMS_People_ID__c = 122222;
                update product;
        }
            throw new TestException('Failed to throw correctly');
        } catch (Exception e) {
            String errorMessage = e.getMessage();
            Boolean validError = errorMessage.contains('You cannot edit XXXX Products and Services record.');
            System.assertEquals(true, validError, 'Validation rule should throw correct error.');
        }

        System.runAs(u){
            product.PIMS_People_ID__c = 122222;
        }
        
       // Test edit of Account Id 
        try {
            System.runAs(u) {
                product.Name = 'Cornerstone';
                product.AccountId = 'ABC Clinic';
                update product;
        }
            throw new TestException('Failed to throw correctly');
        } catch (Exception e) {
            String errorMessage = e.getMessage();
            Boolean validError = errorMessage.contains('You cannot edit XXXX Products and Services record.');
            System.assertEquals(true, validError, 'Validation rule should throw correct error.');
        }

        System.runAs(u){
            product.AccountId = 'ABC Test Clinic';
        }

 
Dear Community

I wonder if you could assit me with the test class. 

I am wrrting the test class for the Validation rule.  User with Certain Permision Set is blocked from editing fields. I would like to set test user, assign him to the permission set  and insert test account.   This is just the first line of the Tast Class.    

I am getting 2 errors: 

line  43   Expecting  '}' but was insert 
line 41 Variable  u  does not exist  
Would you know how to resolve it? 
@isTest
public class Test_VR_FSRNAAssetBlockEdit {

    static final string PERM_SET = 'FSR_NA_DBR_Setup_and_Installation_Permissions';
    
    
    @testSetup
    public static void dataSetup() {
      // create test user with Field Support Rep NA profile 
    Profile FSRNA = [SELECT Id, Name FROM Profile WHERE Name = 'Field Support Rep - CAG'];
        

        User u = new User(
            Alias = 'CTSvTest',
            Email = 'TestAssetValidationRuleFSRNA@idexx.com',
            Username = 'TestAssetValidationRS@idexx.com',
            FirstName = 'CTS Test',
            LastName = 'UserAssetVR',
            TimeZoneSidKey = 'America/New_York',
            LocaleSidKey = 'en_US',
            EmailEncodingKey = 'UTF-8',
            LanguageLocaleKey = 'en_US',
            ProfileId = FSRNA.Id
        );

        insert u;

        // Make Account
        Account acc = new Account();
        acc.Name = 'TestAccount';

        System.runAs(u) {
            insert acc;
        }
    }
         // need to assign user to permission set
        PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = :PERM_SET];
    
        PermissionSetAssignment psa = new PermissionSetAssignment(
        PermissionSetId = ps.Id,
        AssigneeId = u.Id
        );
        insert psa;
    }   
}
    @IsTest
    static void Test_



 
Dear Community, 

I wonder if someone can assit me with the Test Class I am wrrting for a Process Builder.  

User creates a Task from a Case 
Status od The Task Open 
Field Queue (picklist) s populated) with Backoffice UK Ref Lab Support
Record Type of Task is  CAG EMEA Lab Services Escalation Task. 

We would like to test if this Task is indeed assigne fto the Task Queue (  Backoffice UK Ref Lab Support) 

I am getting error  Error: Compile Error: A non foreign key field cannot be referenced in a path expression: OwnerId at line 36 column 43

How would I fix the error? 

Any help is much appriciated. 
Thank you
Kasia 
@isTest
public class Test_PB_Task_CAGEMAQueueRouting {
    @testSetup
    static void TaskCreateData(){
        
        //Case creation
        Case c = new Case(Subject='Test Case');
        c.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('CAG Lab Services Case').getRecordTypeId();
        insert c;
}     
    
    @isTest
    static void ValidTaskTest(){
       
        Id taskOwnerId = [SELECT Id FROM User WHERE Name = 'test user'].Id;
        
        //Task Creation
        Task taskObj = new Task();
        taskObj.Subject = 'Test';
        taskObj.Queue__c = 'Backoffice UK Ref Lab Support';
        taskObj.OwnerId = TaskOwnerId;
        taskObj.Status = 'Open';
        taskObj.RecordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('CAG EMEA Lab Services Escalation Task').getRecordTypeId();
        
        Test.startTest();
        insert taskObj;
      Test.stopTest();
        //fetching task details 
        Task taskUpdateObj = [SELECT Id,OwnerId
                                         FROM Task LIMIT 1];
        system.assertEquals(taskUpdateObj.OwnerId.Name,'Backoffice UK Ref Lab Support');
        
    }
   }

 
Dear Community

Hope you can assit me with resoloving the error messge for the test class

I want to confim that inserted custom Object for test account (where Account Shipping Code is GB) has a correct Email Address updated under custom field: ISAM team to be notified . I am getting error 
Error MessageSystem.AssertException: Assertion Failed: Expected: ISAMS-UK@idexx.com, Actual: isams-uk@idexx.com
Stack TraceClass.Test_PB_CMFUPdateISAMEmail.testCountryGB: line 35, column 1

Would you know how this should fixed? 
@isTest
public class Test_PB_CMFUPdateISAMEmail {
   //tests the following: 
   //Process Builder : "EU - EMEA CMF Updates"
   //test is only for 1 Action update field on CMF Form  ISAM team to be notified based on account country 
   
   
    @TestSetup static void setup() {
        //Create an Account
        Account testAccount = new Account(
          RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Customer').getRecordTypeId(),
            Name = 'Test Account',
            SAP_Customer_Number__c ='0012345678',
            ShippingCountryCode =  'GB'
      );
        insert testAccount;
        
        //Create Cusotmer Master fiele Update record with 1 of the countires GB
        Customer_Master_File_Update__c testCMF = new Customer_Master_File_Update__c(
            Name = 'test',
            RecordTypeId = Schema.SObjectType.Customer_Master_File_Update__c.getRecordTypeInfosByName().get('Change of Fiscal Data').getRecordTypeId(),
            Account_To_Update__c = testAccount.Id
           
        );
        insert testCMF;
       
               
  }

    //Tests condition Customer Master  file Account Shipping Country = 'GB'
    @isTest
    static void testCountryGB(){
        Test.startTest();
          Customer_Master_File_Update__c testCMF = [SELECT Id, ISAM_team_to_be_notified__c FROM Customer_Master_File_Update__c];   
          system.assertEquals('ISAMS-UK@idexx.com', testCMF.ISAM_team_to_be_notified__c );          
        Test.stopTest();  
    }
}





   
Dear Community
I am new to writting test classes and I am hoping for your assistance.  
Here is the test class for Assigning Pemssion set to the user based on the User Role. 
It passes  the test but i was advised to update the class to include te assert to prove that the code (in case the flow) performed the actions i expected it to. I am struggling.  
Would you advise how the assert should look like for permision set  assigemnt to the user?  Any help is much appriciated. thank you Kasia 
       

@isTest 
private class Test_Flow_PermissionSetAnimana {
    static testMethod void checkPermissionSetAssigment () {
        List<PermissionSetAssignment> permissionSetList = new List<PermissionSetAssignment>();
        Id permissionSetId = [SELECT Id FROM PermissionSet WHERE Name = 'CAG_EMEA_Animana_Sales_Livestock_Doctors_Access'].Id;
        for (User u : [SELECT ID,UserRole.Name,Profile.Name,IsActive FROM User WHERE  UserRole.Name LIKE 'CAG EMEA Animana CS Rep' AND Profile.Name = 'Field Sales Rep- CAG EMEA' AND IsActive = TRUE]){
            PermissionSetAssignment psa = new PermissionSetAssignment (PermissionSetId = permissionSetId, AssigneeId = u.Id);
            permissionSetList.add(psa);
        }
        try{
            upsert permissionSetList;
        }catch(exception e){
            system.debug('exception caught' + e);
        }
    }
}
Dear Community,
I am working on the test class for the Process Builder  with Flow where I assign the User with specific role to the Permission set called Permission Set Name   CAG EMEA Animana Sales Livestock Doctors Access

( Or  Developer  Name: CAG_EMEA_Animana_Sales_Livestock_Doctors_Access) 

This test class passed but I was asked to modify it and  use Permisison Set name or Developer Name  instead of PermissionSetId 

How would I need to update the class ? Would you guide me in the right direction? 


@isTest (SeeAllData = true)
private class Test_Flow_PermissionSetAnimana
{
    static testMethod void checkPermissionSetAssigment()
{
 List<PermissionSetAssignment> permissionSetList = new List<PermissionSetAssignment>();
for (User u : [SELECT ID,UserRole.Name,Profile.Name,IsActive FROM User WHERE  UserRole.Name LIKE 'CAG EMEA Animana CS Rep' AND Profile.Name = 'Field Sales Rep- CAG EMEA' AND IsActive = true]){ 
    PermissionSetAssignment psa = new PermissionSetAssignment (PermissionSetId = '0PS2g0000001QC1', AssigneeId = u.Id);
    permissionSetList.add(psa);
}
try{
    upsert permissionSetList;
}catch(exception e){
    system.debug('exception caught' + e);
    }
    }
    }

Thank  you
Kasia 
Hi  I hope  someone can help me here .  I am new to writting test classes.  

My test class is falinig do to  following error. 
System.QueryException: List has no rows for assignment to SObject  ( line 4, column 1) 

In this test,  User with Role  CAG EMEA Animana CS Rep  should be blocked from  editing field on the  account page: Number of Doctors. 

@istest
private class Test_VR_DontAllowEditforAnimana {
    private static testmethod void updateAccount(){
        User testUser = [Select Id,UserRole.Name,Profile.Name From User 
                        Where UserRole.Name = 'CAG EMEA Animana CS Rep' 
                        AND Profile.Name = 'Field Sales Rep- CAG EMEA'
                        AND Reporting_Role__c = 'FSR DX'
                        AND isActive = true LIMIT 1];

        insert testUser;

        Account testAccount = [SELECT Id FROM Account WHERE Name = 'Test Account' AND SAP_Customer_Number__c ='5678111111' LIMIT 1];
        Insert testAccount;
        Test.startTest();
        system.runAs(testUser){
            
              testAccount = New Account(Number_of_Doctors__c  = 2.00);
            try{
                update testAccount;    
            }catch(Exception e){
                system.debug(e.getMessage());
                system.assertEquals(true,e.getMessage().contains('This modification is not allowed. Please contact your CAG colleague for this field.'));
            }
            System.assertEquals(null,testAccount.id);
            
            
        }
         test.stopTest();
        
    }
}
 


 
Hello 
Hoping that you can help me!
I would like to modify this Validation rule to use for example Case Record Type Name or  Case Record Type Developer Name instead of hardcoded Ids.  

When I tried to replace RecordTypeId = '0123Z000000LKZa' with RecordType.Name I received the error:
PRIORVALUE function cannot reference the RecordType.Name field.

Here is my validation rule: 

AND
(
RecordTypeId = '0123Z000000LKZb',
ISCHANGED(RecordTypeId),
PRIORVALUE(RecordTypeId) = '0123Z000000LKZa',
$Profile.Name <> "System Administrator",
$Profile.Name <> "System Integration",
$Profile.Name <> "CRM Team"

)
Hi I am trying to mass update Knowledge Articles from Published to Drafts  (Developer Console: Debug> Execute Anonymos Windwow) 
Its been working succesfully with smaller updates until when I got about 1600 articles to update.
List<Knowledge__kav> articleIds = [SELECT Id,Region__c,LastPublishedDate,Line_of_business__c,Title, KnowledgeArticleId FROM Knowledge__kav WHERE PublishStatus = 'Online' AND Title <> 'Digital Cytology: Slide Scanning' AND Title <> 'SNAP Tests: Universal SNAP Protocol Checklist' AND Title <> 'SNAPShot Dx: Streaking and/or Speckling' AND Title <> 'This is a test of LOB and Region' AND Title <> 'SNAPShot Dx: Streaking and/or Speckling' AND Title <> 'Cornerstone: Lab results run under the wrong patient - wrong patient on lab report PDF' AND  Line_of_business__c ='' AND  Language = 'en_US' WITH DATA CATEGORY Line_of_Business__c AT (IHD__c) LIMIT 100];
for(Knowledge__kav article : articleIds){
KBManagement.PublishingService.editOnlineArticle(article.KnowledgeArticleId, true);
}
system.Debug(articleIds.size());



I am getting the follwoing error. 

System.HandledException: You can't perform this action. Be sure the action is valid for the current state of the article, and that you have permission to perform it.

I think we may be running into "one or more of those online article already has a draft article" issue mentioned here: https://salesforce.stackexchange.com/questions/115592/mass-updating-published-articles

I am new to apex code.  Would you advise how to modify the exsiting code i have to use Try and Catch ? Thank you in advance for your help. 

Kasia 

 
Dear community

I am writting the test cass for Knoweldge Article.  
In the test class i am trying to instert Knowledge  article and test if the 2 custom field are being auto popualted.

If user who creates an article  has a certian profile, 2 custom fields on Knowledge articles l will be automaticlly populated: Region (North America)  and Line of busines (VSS).
 
@isTest
public class Test_PB_KnowledgeLOBnadRegionUpdates {
    //Tests the node "testVSSNA"
    @isTest
    static void testVSSNA(){
        Test.startTest();
        Profile p = [select id from Profile where profile.name='Customer and Technical Support - CAG NA'];
        User userVSSNA = [SELECT Id from User where ProfileId = :p.id AND IsActive = TRUE limit 1];
        System.runAs(userVSSNA){
          //Create a General Article
          Knowledge__kav testKnowledgeArticle = new Knowledge__kav(
                 RecordTypeId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('General').getRecordTypeId(),
                 Title = 'TestVSSNA',
                 UrlName = 'salesforce-crm',
                 Summary = 'Salesforce Cloud CRM',
                 Language = 'en_US'
              
          );
          insert testKnowledgeArticle;

            // Test if Region is North America and Line of Business is VSS
           Knowledge__kav testArticle =  [SELECT Id,Line_of_Business_c, Region_c FROM KnowledgeArticle WHERE Title = 'TestVSSNA'];
        
            System.assertEquals(testArticle.Line_of_Business_c, 'VSS');
            system.assertEquals(testArticle.Region_c, 'North America');
        Test.stopTest();        
    } 
  }
}
I am getting 3 errors: see screeshot below.  Would  you be able to assit how i can resolve the issues?  thank you in advance. 

best Kasia

User-added image
Dear Community

I wonder if you could assit me with the test class. 

I am wrrting the test class for the Validation rule.  User with Certain Permision Set is blocked from editing fields. I would like to set test user, assign him to the permission set  and insert test account.   This is just the first line of the Tast Class.    

I am getting 2 errors: 

line  43   Expecting  '}' but was insert 
line 41 Variable  u  does not exist  
Would you know how to resolve it? 
@isTest
public class Test_VR_FSRNAAssetBlockEdit {

    static final string PERM_SET = 'FSR_NA_DBR_Setup_and_Installation_Permissions';
    
    
    @testSetup
    public static void dataSetup() {
      // create test user with Field Support Rep NA profile 
    Profile FSRNA = [SELECT Id, Name FROM Profile WHERE Name = 'Field Support Rep - CAG'];
        

        User u = new User(
            Alias = 'CTSvTest',
            Email = 'TestAssetValidationRuleFSRNA@idexx.com',
            Username = 'TestAssetValidationRS@idexx.com',
            FirstName = 'CTS Test',
            LastName = 'UserAssetVR',
            TimeZoneSidKey = 'America/New_York',
            LocaleSidKey = 'en_US',
            EmailEncodingKey = 'UTF-8',
            LanguageLocaleKey = 'en_US',
            ProfileId = FSRNA.Id
        );

        insert u;

        // Make Account
        Account acc = new Account();
        acc.Name = 'TestAccount';

        System.runAs(u) {
            insert acc;
        }
    }
         // need to assign user to permission set
        PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = :PERM_SET];
    
        PermissionSetAssignment psa = new PermissionSetAssignment(
        PermissionSetId = ps.Id,
        AssigneeId = u.Id
        );
        insert psa;
    }   
}
    @IsTest
    static void Test_



 
Dear Community

Hope you can assit me with resoloving the error messge for the test class

I want to confim that inserted custom Object for test account (where Account Shipping Code is GB) has a correct Email Address updated under custom field: ISAM team to be notified . I am getting error 
Error MessageSystem.AssertException: Assertion Failed: Expected: ISAMS-UK@idexx.com, Actual: isams-uk@idexx.com
Stack TraceClass.Test_PB_CMFUPdateISAMEmail.testCountryGB: line 35, column 1

Would you know how this should fixed? 
@isTest
public class Test_PB_CMFUPdateISAMEmail {
   //tests the following: 
   //Process Builder : "EU - EMEA CMF Updates"
   //test is only for 1 Action update field on CMF Form  ISAM team to be notified based on account country 
   
   
    @TestSetup static void setup() {
        //Create an Account
        Account testAccount = new Account(
          RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Customer').getRecordTypeId(),
            Name = 'Test Account',
            SAP_Customer_Number__c ='0012345678',
            ShippingCountryCode =  'GB'
      );
        insert testAccount;
        
        //Create Cusotmer Master fiele Update record with 1 of the countires GB
        Customer_Master_File_Update__c testCMF = new Customer_Master_File_Update__c(
            Name = 'test',
            RecordTypeId = Schema.SObjectType.Customer_Master_File_Update__c.getRecordTypeInfosByName().get('Change of Fiscal Data').getRecordTypeId(),
            Account_To_Update__c = testAccount.Id
           
        );
        insert testCMF;
       
               
  }

    //Tests condition Customer Master  file Account Shipping Country = 'GB'
    @isTest
    static void testCountryGB(){
        Test.startTest();
          Customer_Master_File_Update__c testCMF = [SELECT Id, ISAM_team_to_be_notified__c FROM Customer_Master_File_Update__c];   
          system.assertEquals('ISAMS-UK@idexx.com', testCMF.ISAM_team_to_be_notified__c );          
        Test.stopTest();  
    }
}





   
Dear Community
I am new to writting test classes and I am hoping for your assistance.  
Here is the test class for Assigning Pemssion set to the user based on the User Role. 
It passes  the test but i was advised to update the class to include te assert to prove that the code (in case the flow) performed the actions i expected it to. I am struggling.  
Would you advise how the assert should look like for permision set  assigemnt to the user?  Any help is much appriciated. thank you Kasia 
       

@isTest 
private class Test_Flow_PermissionSetAnimana {
    static testMethod void checkPermissionSetAssigment () {
        List<PermissionSetAssignment> permissionSetList = new List<PermissionSetAssignment>();
        Id permissionSetId = [SELECT Id FROM PermissionSet WHERE Name = 'CAG_EMEA_Animana_Sales_Livestock_Doctors_Access'].Id;
        for (User u : [SELECT ID,UserRole.Name,Profile.Name,IsActive FROM User WHERE  UserRole.Name LIKE 'CAG EMEA Animana CS Rep' AND Profile.Name = 'Field Sales Rep- CAG EMEA' AND IsActive = TRUE]){
            PermissionSetAssignment psa = new PermissionSetAssignment (PermissionSetId = permissionSetId, AssigneeId = u.Id);
            permissionSetList.add(psa);
        }
        try{
            upsert permissionSetList;
        }catch(exception e){
            system.debug('exception caught' + e);
        }
    }
}
Dear Community,
I am working on the test class for the Process Builder  with Flow where I assign the User with specific role to the Permission set called Permission Set Name   CAG EMEA Animana Sales Livestock Doctors Access

( Or  Developer  Name: CAG_EMEA_Animana_Sales_Livestock_Doctors_Access) 

This test class passed but I was asked to modify it and  use Permisison Set name or Developer Name  instead of PermissionSetId 

How would I need to update the class ? Would you guide me in the right direction? 


@isTest (SeeAllData = true)
private class Test_Flow_PermissionSetAnimana
{
    static testMethod void checkPermissionSetAssigment()
{
 List<PermissionSetAssignment> permissionSetList = new List<PermissionSetAssignment>();
for (User u : [SELECT ID,UserRole.Name,Profile.Name,IsActive FROM User WHERE  UserRole.Name LIKE 'CAG EMEA Animana CS Rep' AND Profile.Name = 'Field Sales Rep- CAG EMEA' AND IsActive = true]){ 
    PermissionSetAssignment psa = new PermissionSetAssignment (PermissionSetId = '0PS2g0000001QC1', AssigneeId = u.Id);
    permissionSetList.add(psa);
}
try{
    upsert permissionSetList;
}catch(exception e){
    system.debug('exception caught' + e);
    }
    }
    }

Thank  you
Kasia 
Hi  I hope  someone can help me here .  I am new to writting test classes.  

My test class is falinig do to  following error. 
System.QueryException: List has no rows for assignment to SObject  ( line 4, column 1) 

In this test,  User with Role  CAG EMEA Animana CS Rep  should be blocked from  editing field on the  account page: Number of Doctors. 

@istest
private class Test_VR_DontAllowEditforAnimana {
    private static testmethod void updateAccount(){
        User testUser = [Select Id,UserRole.Name,Profile.Name From User 
                        Where UserRole.Name = 'CAG EMEA Animana CS Rep' 
                        AND Profile.Name = 'Field Sales Rep- CAG EMEA'
                        AND Reporting_Role__c = 'FSR DX'
                        AND isActive = true LIMIT 1];

        insert testUser;

        Account testAccount = [SELECT Id FROM Account WHERE Name = 'Test Account' AND SAP_Customer_Number__c ='5678111111' LIMIT 1];
        Insert testAccount;
        Test.startTest();
        system.runAs(testUser){
            
              testAccount = New Account(Number_of_Doctors__c  = 2.00);
            try{
                update testAccount;    
            }catch(Exception e){
                system.debug(e.getMessage());
                system.assertEquals(true,e.getMessage().contains('This modification is not allowed. Please contact your CAG colleague for this field.'));
            }
            System.assertEquals(null,testAccount.id);
            
            
        }
         test.stopTest();
        
    }
}