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
Chetna AgrawalChetna Agrawal 

I want to create sobject in test class.

can't really do something like:
Schema.getGlobalDescribe().get(ObjectName).newSObject() ;
Abhishek BansalAbhishek Bansal
Hi Chetna,

You can use the below code to create Sobject in test class:
// Create an account with predefined default values
Account acct = (Account)Account.sObjectType.newSObject(null, true);
// Provide a value for Name
acct.Name = 'Acme';
// Insert new account
insert acct;

// This is for record type RT1 of Account
ID rtId = [SELECT Id FROM RecordType WHERE sObjectType='Account' AND Name='RT1'].Id;
Account acct2 = (Account)Account.sObjectType.newSObject(rtId, true);
// Provide a value for Name
acct2.Name = 'Acme2';
// Insert new account
insert acct2;
In place of Account you can use your custom object for which you want to create test Sobject.
Please find more help on below link :
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Schema_SObjectType.htm

Let me know if you need more help.

Thanks,
Abhishek
Chetna AgrawalChetna Agrawal
Thanks. but i want this for dynamic sobject.
i am taking currentpageid and object name from that id in my controller:
 currentPageId =ApexPages.currentPage().getParameters().get('Id');
ObjName = id.ValueOf(currentPageId).getSObjectType().getDescribe().getName();
Anirudh SinghAnirudh Singh
Hi Chetna,

Try this:
//Get the Id from the parameter passed to the page.
String currentPageId=ApexPages.currentPage().getParameters().get('Id');

//Convert the String value to Id.
Id currentRecordId=Id.valueOf(currentPageId);

//Get the Object Name.
String sObjName=currentRecordId.getSObjectType().getDescribe().getName();

//Global Describe Map.
Map<String, Schema.SObjectType> globalDescMap=Schema.getGlobalDescribe();

//Get the sObjectType. This is used for creating sObject.
Schema.SObjectType targetType=globalDescMap.get(sObjName);

//Create new sObject.
sObject sObj=targetType.newSObject();

Please let me know if this helps.
If yes, please mark the Question as Solved.


Thanks and Regards,
Anirudh Singh