Test class code coverage for lookup field and URL field

apexcode-coverageunit-test

In my simple use case I am unable to get code coverage for Account and URL fields any suggestions. In the URL field I am appending string what I get from the form to the URL field.
Here's the code for my apex class and test class::

public without sharing class Create_Deal{
   public static string saveRecord(Deal__c itemd){
        string url = 'https://www.amazon.com/s/p-';
        map<string,string> info = new map<string,string>();
        List<Account> results = [SELECT id FROM Account WHERE Account_ID__c = : itemd.Seller_ID__c];
        if (results.size() != 0){
            itemd.Account__c  = results.get(0).id;
            itemd.SPM_ID__c  = url + itemd.Sears_Item_SPM_or_A__c; 
            try{  
               insert itemd;
               //return itemd.id;
               info.put('status','success');
               info.put('message',itemd.id);
            } catch(exception e) { 
               system.debug('-------getMessage-----------'+e.getMessage());
            }

TEST CLASS::

@isTest
private class Create_Deal_Test{
   static testMethod void test_saveRecord_UseCase1(){
      Account itdAct = new Account() ;
      itdAct.Name = '123Cycles';
      itdAct.Account_ID__c = '12332';
      insert itdAct;
      Deal__c itmd = new Item_Deal__c(Seller_ID__c='1234',Email__c = '[email protected]', price__c = 23211, Category__c = 'vert', Item_Description__c = 'Itemdescription' );
      itmd.Account__c = itdAct.Id;
      itmd.SPM_ID__c = 'www.amazon.com';
      insert itmd;
      Create_Deal.saveRecord(itmd);
   }
}

Best Answer

In your case, during executing test class this query [SELECT id FROM Account WHERE Account_ID__c = : itemd.Seller_ID__c] returns nothing.

In order to cover these lines:

itemd.Account__c  = results.get(0).id;
itemd.SPM_ID__c  = url + itemd.Sears_Item_SPM_or_A__c;
...

You need to assign Seller_ID__c for your Deal with the same value as for Account_ID__c.

Therefore, your test method should look something like this:

// Assign same seller id for Account and Deal__c
String sellerId = '1234';

Account itdAct = new Account(
    Name = '123Cycles',
    Account_ID__c = sellerId
);
insert itdAct;

Deal__c itmd = new Item_Deal__c(
    Seller_ID__c = sellerId,
    Email__c = '[email protected]',
    price__c = 23211,
    Category__c = 'vert',
    Item_Description__c = 'Itemdescription',
    Account__c = itdAct.Id,
    SPM_ID__c = 'www.amazon.com'
);
insert itmd;

Create_Deal.saveRecord(itmd);

But, to be honest, I don't understand why you need Account_ID__c field since you can just use relationship to the account in the query:

[SELECT id FROM Account WHERE Id = : itemd.Account__c]
Related Topic