I have a test that is failing and was previously working. I have two decimal fields on a custom object, let us call them Field1__c and Field2__c. I then have Field3__c with a formula.

MyObject__c.Field3__c formula

BLANKVALUE(Field1__c, 0) + BLANKVALUE(Field2__c, 0)

In my test I create the object, perform some calculations, and get to this point:


MyObject__c o = ...;
// Field1__c gets set in the class being tested.
o.Field2__c = 0;

// These pass
System.assert(o.Field1__c == 2);
System.assert(o.Field2__c == 0);
System.assert(o.Field1__c + o.Field2__c == 2);

// Fail: value is null
System.assert(o.Field3__c == 2, 'Expected = 2, actual = ' + o.Field3__c);

How is this possible? Fields 1 and 2 have values, and the assertions prove it. The formula is simply adding the values, converting null to 0 in the process. But they are not null: how can the result be null?

This was working just fine a week ago. I think this org might be possessed because I have noticed several other oddities I am still investigating. This org is on Summer '14, and I have a feeling some of the weird stuff I have seen is related to the fact it was upgraded a few weeks ago.

  • I believe in order to test a formula field, you must query the object. Simply changing the value of a dependent field in memory will not recalculate the formula. Try this test: MyObject__c o = new MyObject__c(Field1__c = 2, Field_2__c = 0); insert o; o = [select Field1__c, Field2__c, Field3__c from MyObject__c where id = :o.id]; // repeat asserts from original test – Jason Clark Jul 31 '14 at 19:44

Formula fields do not automatically get calculated in test classes.

However, if you requery the object the assert will pass.

  • That did it. I wonder how this worked before, then? The code was literally unchanged from a month ago, and it was passing at that time when I wrote the test. – user6861 Jul 31 '14 at 19:48

is it possible you don't have permission to see field3?

  • All profiles have access to the field. – user6861 Jul 31 '14 at 19:45

Your Answer

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