[SalesForce] Auto number name shows up null in the test class

I have a custom object where record name is auto generated. In a test class I am creating a record of that object and then calling another method from another class where this record is being used. That method throws error saying "Argument cannot be null". The created record has no name (or null name).

I cannot do record.Name = 'Test' as it shows an error saying "Field is not writable".

Any idea why the record name is null in the test class and how I solve it?

Code:

@isTest
private class MyTestClass {
    private static testMethod void test() {
        CustomObj__c obj = new CustomObj__c();
        obj.Field1__c = 'value';
        //so on
        insert obj;

        Boolean flag = SomeClassThatUsesCustomObj.StaticMethod(obj);
        System.assertsEqual(true, flag);
    }
}

When the static method of the SomeClassThatUsesCustomObj is running, it needs the name of the obj record. But since it is auto number, it comes out to be null and hence throws an exception and the test class fails.

Best Answer

If you want to mock an SObject with an auto-number field pre-filled in, do the following

Foo__c foo = (Foo__c) Json.deserialize('{"name" : "abc"}',Foo__c.class);

This is an object in memory, not in the database. You can add additional fields to mock in the JSON string expression.

Note that the JSON value for "name" doesn't even have to adhere to the auto-number format for the object.

UPDATE - when you need to insert the mocked SObject

@isTest
private class MyTestClass {
    private static testMethod void test() {
        CustomObj__c obj = new CustomObj__c();
        obj.Field1__c = 'value';
        //so on
        insert obj;
        obj = [select id, field1__c, name from CustomObj__c where id = :obj.id LIMIT 1]; // add this line

        Boolean flag = SomeClassThatUsesCustomObj.StaticMethod(obj);
        System.assertsEqual(true, flag);
    }
}

Auto-number field values of mocked SObjects must be queried before they can be referenced later in the code path. Note that @FernandoGavinho had this answer first

Related Topic