+ Start a Discussion
Manjunath SC 5Manjunath SC 5 

How to write test class for contact creation of new account trigger

Hello guys

i am new to the coding, i want to write test class for contact creation on new account, below is my code

trigger ConOnNewAcc on Account (after insert){
    Public List<Contact> con = new List<Contact>();
    For(Account Acc:Trigger.new ){
        Contact c=new contact();
        c.accountid=acc.id;
        c.Lastname=acc.Name;
        con.add(c);
    }
    Insert Con;
}
 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Manjunath,

Greetings to you!

Please try below code:
@isTest
public class Test_ConOnNewAcc {
    
    static testMethod void testMethod1() {
        // Please add all required field
        Account acc = new Account();
        acc.Name = 'TestAcc';
        INSERT acc;
        
        // Please add all required field
        Contact con = new Contact();
        con.LastName = acc.Name;
        con.AccountId = acc.Id;
        INSERT con;
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Deepali KulshresthaDeepali Kulshrestha
Hi Manjunath,


I have gone through your problem, Please try below code:
@isTest
public class ConOnNewAcc_Test {

    @isTest static void testConOnAcc()
    {
        List<Account> acc_List = new List<Account>();
        for(Integer i=0;i<2;i++)
        {
            Account acc = new Account();
            acc.Name='testAcc'+i;
            acc_List.add(acc);
        }
        
        Test.startTest();
        DataBase.SaveResult[] results = Database.insert(acc_List, false);
        System.debug('Results is ::::'+results);
        Test.stopTest();
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com
Ajay K DubediAjay K Dubedi
Hi Manjunath,

I looked at your query. I have created a test class that should work fine in your case.
Here is my code - 
//Test Class - 

@isTest
public class ConOnNewAccTest {
    @isTest
    public static void testTrigger() {
        List<Account> accList = new List<Account>();
        Set<Id> accIds = new Set<Id>();
        for(integer i=0;i<10;i++) {
            accList.add(new Account(Name='TestAccount'+i));
        }
        insert accList;
        for(Account acc: accList) {
            accIds.add(acc.Id);
        }
        List<Contact> conList = new List<Contact>([Select Id, AccountId From Contact Where AccountId In :accIds]); 
        System.assertEquals(10, conList.size());
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com