0

I am not sure how to create multiple profiles for one hierarchy custom setting. I assume it would look something like this:

    ConcurrentSessionsPolicyLimit__c defaultLimit = new ConcurrentSessionsPolicyLimit__c();
    defaultLimit.Login_Attempts_Limit__c = 1;
    defaultLimit.Name= 'ConcurrentSessionsPolicyLimit';
    defaultLimit.SetupOwnerId=Userinfo.getUserId();
    insert defaultLimit; 

    defaultLimit = new ConcurrentSessionsPolicyLimit__c(Id = defaultLimit.Id, Name = 'System Administrator', Login_Attempts_Limit__c= 5);
    defaultLimit = new ConcurrentSessionsPolicyLimit__c(Id = defaultLimit.Id, Name = 'Campaign Manager', Login_Attempts_Limit__c = 2);
    update defaultLimit;

but when I do this, I am returned 4 ConcurrentSessionsPolicyLimit__c and they are being overwritten. I am not upserting the test data correctly, can anyone correct what I am doing wrong? Do I need to explicitly set defaultLimit[0] = _______? or defaultLimit.add(___?);

I have done a fair amount of googling and it all points to a single instance of the hierarchy custom setting.

How to create Hierarchy custom settings in Apex

2 Answers 2

2

To create multiple hierarchical custom settings for multiple profiles for use in Unit tests...

insert new List<ConcurrentSessionsPolicyLimit__c> {
  new ConcurrentSessionsPolicyLimit__c(
    SetupOwnerId = [SELECT id FROM Profile WHERE Name = 'profileA'][0].Id,
    Login_Attempts_Limit__c = someVal),
  new ConcurrentSessionsPolicyLimit__c(
    SetupOwnerId = [SELECT id FROM Profile WHERE Name = 'profileB'][0].Id,
    Login_Attempts_Limit__c = someVal),
  ...
} 
1

Since you're asking about unit tests, what you need to know is that you'll need to create new instances of custom settings for your unit tests. You can't assume the unit test will be able to read them from the org except perhaps for a default value. It will know what the fields are, but not what any of the data sets are.

Its preferable to create the test data in an @testSetup static void setup() method or in an @isTest public class TestDataFactory that you call from within your unit test class. See Using Test Setup Methods and also Common Test Utility Classes for Test Data Creation in the docs for more on those two particular options for Test Data Creation.

And in the case of Hierarchy Custom Settings, you'll want to remember that Hierarchy Custom Settings behave differently than List Custom Settings. See Custom Settings Methods in the docs for more. Hierarchy settings will be by User, etc. and List Custom Settings should each be named. If not named, they would be in an array as you've noted which doesn't apply to what you're attempting to do with Hierarchy Custom Settings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.