function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MaverickDevMaverickDev 

Test Coverage for custom settings

Hi Guys,

 

The issue I'm having is very typical and simple but I'm not getting 100% test coverage for the same.

 

I've developed custom setting with Protected visibility and Hierarchy setting type and have few fields defined in it.

e.g. UserID, AccessToken, ExpireTime, SHA1Key, etc.

 

When I tried to write test coverage class, it gives an exception of DUPLICATE SetupOwnerID, so my test coverage is not able to get 100% code coverage. Here is my test code written below;

 

 

profile p = [select id from profile where name='System Administrator'];
User thisUser = [ Select Id from User where Id = :UserInfo.getUserId() ];              System.runAs( thisUser ){       UserDetails__c aUser =  UserDetails__c.getInstance();
          if(aUser == null) {
                aUser = new UserDetails__c();
                aUser.AccessToken__c = 'c6cf8cf235d4daedb0b7556ea48355cb0fa51f71';
                aUser.ID__c = '2040';
                aUser.SFUserID__c = UserInfo.getUserId();
                aUser.URL__c ='http://www.google.com';
                aUser.Sha1Key__c = '2228238edfa898d44d3fa1d7aec93c078bac281';
                aUser.SetupOwnerId = p.id;
                aUser.ExpiresIn__c = 1000.00;            
                insert aUser;
                
                aUser = [SELECT Name__c, AccessToken__c, SetupOwnerId FROM UserDetails__c WHERE SFUserID__c =  UserInfo.getUserId() LIMIT 1];    
                System.assertEquals('2228238edfa898d44d3fa1d7aec93c078bac281', Sha1Key__c);}

 

Let me know what is the proper way to do it?

Thanks

 

 

sfdcfoxsfdcfox

It's likely that aUser with a SetupOwnerId of p.id (profile id) already exists, but getInstance() is going to set a new record to userinfo.getuserid(), so when you override this by setting it back to p.id, you end up trying to create a duplicate. Either delete getInstance( p.id ) if its ID is not null, use getInstance( p.id ), don't set SeupOwnerId, or use the upsert call to make sure that if it's a duplicate it will be updated without fail.

SammyComesHereSammyComesHere

Please upgrade to API version 24. 

It stops test classes and individual test methods access to all data in the organization.

 

Quite possible that you have data in Org with same User_Detail__c record