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
sankar Landa 30sankar Landa 30 

Iam want to cover adderror method in test class.I have tried in many ways i can't do it.Some one help me with this.Thanks in Advance

This is my class

trigger ContactActive on contact(before insert, before update){
    for(contact con : trigger.new){
        if(con.accountId != null){
            //Id a = con.accountId;
            list<contact> cList = [SELECT Id, Active__c FROM Contact where Active__c = true and AccountId =: con.accountId];
            if(cList.size() > 0){
                con.addError('no more primary contacts');
            }
        }
        
    }
}

Test Class
------------------
@isTest
public class TestAccountActive {
     static testmethod void testme(){
         account a = new account();
         a.name = 'Test Name';   
         
         insert a;
         contact c =new contact(lastname = 'siva',Active__c = true,accountid = a.id);       
         try{
          insert c;   
            // Database.SaveResult result = Database.insert(c, false);
         }
        catch(Exception e)
          {
          Boolean expectedExceptionThrown = e.getMessage().contains('My Error Message') ? true : false; 
          System.AssertEquals(expectedExceptionThrown, false );
}
  }
   }
Deepak Pandey 13Deepak Pandey 13
@isTest
public class TestAccountActive 
  {
     static testmethod void testme(){
         account a = new account();
         a.name = 'Test Name';   
         insert a;
         
         contact c =new contact(lastname = 'siva',Active__c = true,accountid = a.id);   
          insert c;   
         }
  }
sankar Landa 30sankar Landa 30
HI deepak,
    Thanks for your response but it's not working.
Deepak Pandey 13Deepak Pandey 13
@istest(seealldata=true)
sankar Landa 30sankar Landa 30
still it's not working deepak

 
sankar Landa 30sankar Landa 30
still it's not working deepak