0

In writing a unit test, I have to insert a Journal_c record. Instead of using Ids for several lookup fields, I've run soql queries assuming that the record Ids maybe different from test to production. I am, however, receiving an error when trying to assign both the Product_c and Contact__c fields values via query. The error I receive is "Illegal assignment from LIST to Id. Any help would be appreciated.

            Journal__c gift = new Journal__c();
        gift.RecordType = [SELECT Id, Name FROM RecordType WHERE SObjectType = 'Journal__c' and Name = 'Class Registration'];
        gift.Amount_Applied__c = 500;
        gift.Product__c = [SELECT Id FROM Product__c WHERE Name = 'Gift Certificate']; **Error on this line**
        gift.Contact__c = [SELECT Id FROM Contact WHERE Name = 'Daniel Mortensen']; **Error on this line**
        gift.Journal_Type__c = 'Gift Card';
        gift.Gift_Certificate_Code__c = 'testcode';
        gift.Date__c = system.today();
        gift.Status__c = 'Registration';
        insert gift;

Oddly enough, the RecordType assignment doesn't error out.

1 Answer 1

2

The simple fix is to append .Id to the end of the failing queries. The proper fix would be:

List<RecordType> recordTypes = [SELECT Id, Name FROM RecordType WHERE SObjectType = 'Journal__c' and Name = 'Class Registration'];
List<Product__c> products = [SELECT Id FROM Product__c WHERE Name = 'Gift Certificate'];
List<Contact> contacts = [SELECT Id FROM Contact WHERE Name = 'Daniel Mortensen'];

Journal__c gift = new Journal__c();

if(!recordTypes.isEmpty()) {
  gift.RecordTypeId = recordTypes.get(0).Id;
}

if(!products.isEmpty()) {
  gift.Product__c =  products.get(0).Id;
}

if(!contacts.isEmpty()) {
  gift.Contact__c = contacts.get(0).Id;
}

gift.Amount_Applied__c        = 500;
gift.Journal_Type__c          = 'Gift Card';
gift.Gift_Certificate_Code__c = 'testcode';
gift.Date__c                  = System.today();
gift.Status__c                = 'Registration';
insert gift;

Using this method your code won't error out if one of the queries does not return a result.

2
  • Thanks Phil. I'll accept the answer when it lets me (3 minutes it says). Do you know why the RecordType query doesn't require the .id appending?
    – dannymorty
    Commented Jan 16, 2013 at 15:56
  • because the recordType property is an object, If you'd used recordTypeId, then that would of returned a similar error.
    – superfell
    Commented Jan 16, 2013 at 16:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .