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
test vijaytest vijay 

How to Insert BusinessHours in Apex Class

Hello Guys,
I want to insert new BusinessHours in apex test class but such as i tried to insert BusinessHours from apex error is coming :DML operation Insert not allowed on BusinessHours. 
However, we can create BusinessHours from setup but i want to create Business hours from Apex.
Thanks in advance
VinayVinay (Salesforce Developers) 
Hi Ravi,

Check below examples that can help you to insert business hours.

https://salesforce.stackexchange.com/questions/71771/how-could-i-test-a-businesshours-class-functionality-with-unit-tests
https://salesforce.stackexchange.com/questions/34474/creating-holidays-and-business-hours-in-test-code

Thanks,
test vijaytest vijay
Hi Vinay,
thanks for your response.
I want to cover my following apex class.
public static void testBusinessHours(){
        set<Id> BhIdSet = new Set<Id>();
        for(BusinessHours BH : [SELECT Id,Name FROM BusinessHours WHERE Name = 'Test Business Hours']){
            BhIdSet.add(BH.Id);
        }
        if(BhIdSet.size() > 0){
            For(Contact con : [SELECT Id, Name FROM Contact] ){
                system.debug(con);
            }
        }
        
    }

From test class i am tring className.testBusinessHours(); 
but class is not getting cover with 100%. i don't want to create business hours from setup. does any way to insert business hours in apex test class.
let me know if any way.
Thank You
kalaipriyan boopalankalaipriyan boopalan
Hi , 

can u able to insert Bussiness hours in Apex main class ?