function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
rushi ettam 7rushi ettam 7 

Test class for database upsert

Hello,

I created one class to upsert using databse,but it is only inserting new records in the object not updating
and the test class code coverage is 88% one line is not covering i.e   acc.sic = 'atlanta'; 
can anybody resolve this issue?

public class upsertAccount{
  public static List<Database.upsertResult> upsertAcc(){
    List<Account> acclist = [select id,name,Billingcity,sic from Account where Billingcity = '' ];
    for(Account acc:accList){
      acc.sic = 'atlanta';
      //acclist.add(acc);
    }
    Account newAcc = new Account(name='Acme',Billingcity= 'San Fransicso');
    acclist.add(newAcc);
    Schema.SObjectField schemaField = Account.Fields.SLASerialNumber__c;
List<Database.upsertResult> Results = Database.upsert(acclist ,schemaField ,false);
   return results ; 
  }
 }

Test class

@isTest
public class testUpsertAccount{
  public static testmethod  void testDatabseupsert(){
  List<Database.upsertResult> results =  UpsertAccount.upsertAcc();
  for(Database.upsertResult result:results ){
  system.assert(result.issuccess());
}  
  }
}

Thanks,
Rushi
logontokartiklogontokartik
Hi Rushi, You need to create test data before executing your test class. What you can do is create a method within your test class with annotation @testSetup and create test data or you can do it in your method before you call the UpsertAccount class.
Something like
 
@isTest
public class testUpsertAccount{
 @testSetup
  static void loadTestData() {
    // You can create test data here as well. In your case it will be account data without billingcity
  }
  public static testmethod  void testDatabseupsert(){
     // Create test data here. Create some accounts
     List<Database.upsertResult> results =  UpsertAccount.upsertAcc();
     for(Database.upsertResult result:results ){
     system.assert(result.issuccess());
   }  
  }
}