+ Start a Discussion
Yogesh Dighe.Yogesh Dighe. 

Getting only 66% code coverage. what is wrong in my Test code.??

My Trigger is as following:-

trigger RestrictContactByName on Contact (before insert, before update)
{ //check contacts prior to insert or update for invalid data
For (Contact c : Trigger.New)
{
if(c.LastName == 'INVALIDNAME')
{ //invalidname is invalid
c.AddError('The Last Name "'+c.LastName+'" is not allowed for DML');
}
}
}

--------------------------------------------------
And my Test class as follows:-
@isTest
private class TestRestrictContactByName
{
    @isTest static void TestContact()
    {

        Contact con=new Contact(FirstName='Arjun', LastName='Mahi');
        if(con.LastName=='INVALIDNAME')
        {
             con.AddError('The Last Name "'+con.LastName+'" is not allowed for DML');
            
        }else{insert con;}  
 
        Contact conn=new Contact(FirstName='Arjun', LastName='Kapur');
         if(conn.LastName=='INVALIDNAME')
        {
             conn.AddError('The Last Name "'+conn.LastName+'" is not allowed for DML');
            
        }else {update conn;}  
       
        Contact com=new Contact(FirstName='Rama', LastName='INVALIDNAME');
        
        if(com.LastName=='INVALIDNAME')
        {
             com.AddError('The Last Name "'+com.LastName+'" is not allowed for DML');
            
        }else {insert conn;}
    }
}


plz help me complete this Challenge :)
Thanx in Advance :)
 
Best Answer chosen by Yogesh Dighe.
goabhigogoabhigo
Bhanu, instead of providing simply the code you should have explained it buddy. This forum is not just for solving a problem, its also for making the person understand the logic, features, core concepts, etc. I too have completed the task, and my test class is just 11 lines.
Do keep this in mind and don't give out the code directly.

All Answers

goabhigogoabhigo
I don't understand why you have so many conditions inside your test class itself.

All you have to do is to insert a contact whose LastName is INVALIDNAME. Then catch the exception (.addError throws it). Can't give you the code, but I can help you in understanding what I said.

--
Abhi
Bhanu MaheshBhanu Mahesh
Hi Yogesh,

Try this
@isTest
private class TestRestrictContactByName{
	static testMethod void contactInsertSuccess(){
		Boolean insertFailed;
		Contact con=new Contact(FirstName='Arjun', LastName='Mahi');
		try{
			Test.startTest();
			insert con;
			Test.stopTest();
		}
		catch(Exception e){
			insertFailed = false;
		}
		System.assertEquals(false,insertFailed);
	}
	static testMethod void contactInsertFail(){
		Boolean insertFailed;
		Contact con=new Contact(FirstName='Arjun', LastName='INVALIDNAME');
		try{
			Test.startTest();
			insert con;
			Test.stopTest();
		}
		catch(Exception e){
			insertFailed = true;
		}
		System.assertEquals(true,insertFailed);
	}
}

Regards,
Bhanu Mahesh
goabhigogoabhigo
Bhanu, instead of providing simply the code you should have explained it buddy. This forum is not just for solving a problem, its also for making the person understand the logic, features, core concepts, etc. I too have completed the task, and my test class is just 11 lines.
Do keep this in mind and don't give out the code directly.
This was selected as the best answer
Dushyant SonwarDushyant Sonwar
Hi Yogesh,
Use Database.insert(con) to cover add error Lines in your Test Class...
Yogesh Dighe.Yogesh Dighe.
Thanx Abhi & Bhanu,
Nice 1 Abhi.. :)

and what can i do for the Update .???
goabhigogoabhigo
Hi Yogesh,
For this excercise you dont need to check for update, since there is conditional statement checking for "update" and "insert" (trigger.isInsert or trigger.isUpdate). BUT as a best practise, it's always good to cover these.
So simply insert a contact with any LastName other than INVALIDNAME, then update the contact and make the LastName=INVALIDNAME.
Satya.2020Satya.2020
Hi Yogesh,

Check this out.

@istest
private class TestRestrictContactByName {
    @istest static void testname(){
        contact c = new contact(firstname='Satya',lastname='INVALIDNAME');
        test.startTest();
        database.SaveResult result = database.insert(c,false);
        test.stopTest();
        system.assertEquals('The Last Name "INVALIDNAME" is not allowed for DML', result.getErrors()[0].getMessage());
    }
}
Satya.2020Satya.2020
Hi Yogesh,

In your test case. You are creating a contact for the test case with last name 'Mahi'. So the 'if' condition would never have a last name of INVALIDNAME to be evaluated and I feel the those statements can be removed.

Contact con=new Contact(FirstName='Arjun', LastName='Mahi');
        if(con.LastName=='INVALIDNAME')
        {
             con.AddError('The Last Name "'+con.LastName+'" is not allowed for DML');
            
        }else{insert con;}  

 
Kishan MalepuKishan Malepu
@isTest
private class TestRestrictContactByName {
    @isTest static void createcontact(){
    // Test data setup contact with last name is invalid name
    Test.startTest();
    Contact con = new Contact(LastName ='INVALIDNAME');
    Database.UpsertResult result = Database.upsert(con,false);
        Test.stopTest();
        // Verify 
        // In this case the contact creation should have been stopped by the trigger,
        // so verify that we got back an error.
        System.assert(!result.isSuccess());
        System.assert(result.getErrors().size() > 0);
        System.assertEquals('The Last Name "INVALIDNAME" is not allowed for DML.' ,result.getErrors()[0].getMessage());
      }
}
Thomas HThomas H
Thanks for all the comments in the code Kishan.
 
Chandana LChandana L
Hello 
Try This Code 
-----------------------------------
@isTest
public class TestRestrictContactByName {
    static testmethod void test(){
        Contact con = New Contact(LastName = 'INVALIDNAME');
        Test.startTest();
        insert con;
        Test.stopTest();
    }
}
Thanks 
Siri Chandana
Parikshit SarkarParikshit Sarkar
@Bhanu Mahesh , Thanks for your help! Just tweaked your code a bit since it gave an error for contactInsertSuccess() method. The following test class worked perfectly - 

@isTest
public class TestRestrictContactByName {
    
    @isTest static void insertSuccess(){
        
        boolean insertFailed; 
        
        Contact con = new Contact(
            FirstName = 'John', 
            LastName = 'Travolta'
        );
            
        try{
            Test.startTest(); 
            
            insert(con); 
            
            Test.stopTest(); 
            
        }catch(Exception e){
            insertFailed = null; 
        }
        
        system.assertEquals(null, insertFailed); 
        
    }
    
    @isTest static void insertFailed(){
        
        boolean insertFailed ; 
        
        Contact con = new Contact(
            FirstName = 'John', 
            LastName = 'INVALIDNAME'
        );
        
        try{
            Test.startTest() ; 
            
            insert(con); 
            
            Test.stopTest(); 
        }catch(Exception e){
            insertFailed = true; 
        }
        
        system.assertEquals(true, insertFailed);
    }
    
}
Celio XavierCelio Xavier
Olá, o meu teste deu certo com a cobertura de 100%: 
@isTest
private    class TestRestrictContactByName {
    @isTest static void InvalidName() {
        Contact con = new Contact(LastName='INVALIDNAME');
        Test.startTest();
        Database.SaveResult result = Database.insert(con);
        Test.stopTest();
        System.assert(!result.isSuccess());
        System.assertEquals('The Last Name "INVALIDNAME" is not allowed for DML', result.getErrors()[0].getMessage());
        System.debug('Test Result: ' + result.getErrors()[0].getMessage());
    }

    @isTest static void ValidName() {
        Contact con = new Contact(LastName='Xavier');
        Test.startTest();
        Database.SaveResult result = Database.insert(con);
        Test.stopTest();
        System.assert(result.isSuccess());        
    }    
}