1

I am trying to write a unit test for the following method,

public static DateTime addBusinessDays(DateTime startDate, Integer numberOfDays, String businessHoursName){
         Integer numberOfDaysTobeAdded = 8*3600000*numberOfDays;
         BusinessHours bh = getBusinessHourSettings(businessHoursName);
         Datetime endDate = BusinessHours.add(bh.id,startDate,numberOfDaysTobeAdded);
         return endDate;
    }

My questions are:

  1. Why is the salesforce BusinessHours class doesn't support DML operations?
  2. How could I test a BusinessHours class functionality with unit tests? (without querying the BusinessHours?)
  • salesforce.com/developer/docs/api/Content/… Says it is supports create(), getUpdated(), query(), retrieve(), update() So you should be able to insert – TimChadwick Apr 10 '15 at 7:38
  • 6
    It is annoying that you can not do DML operations on BusinessHours. This question should help. – BarCotter Apr 10 '15 at 7:55
  • I Tried This, BusinessHours bh= new BusinessHours( MondayStartTime = Time.newInstance(9, 0, 0, 0), ............ IsActive = true, IsDefault = true ); insert bh; BUT it says DML not allowed on BusinessHours – Hasantha Apr 13 '15 at 5:30
  • I would rename numberOfDaysToBeAdded to millisecondsToBeAdded... – Adrian Larson Dec 16 '15 at 2:44
  • @TimChadwick Have you ever tried it? It is clearly not allowed and there are a fair amount amount of posts about it out there if you do a little googling. – Adrian Larson Dec 16 '15 at 2:47
1

BusinessHours can't be set up in unit tests.

Best bet is to just set one up in the org and be done with it. Probably all your offices do have a common holiday like 1st January? Then to make your unit test code office-agnostic, you can do something like this:

static Datetime addBusinessDays(Datetime start, Integer time, String office) {

    BusinessHours bh;

    if (Test.isRunningTest()) {
        //for tests
        bh = [SELECT Id FROM BusinessHours LIMIT 1];
    } else {
        //for reals
        bh = [SELECT Id FROM BusinessHours WHERE Name = :office];
    }

    return BusinessHours.add(bh.Id, time, numberOfDays);
}

Then your test data revolves around 1st January to meaningfully assert the correctness of any calculations you want to perform.

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