[SalesForce] Test class for After insert/update Trigger

I have a trigger on Account object which will create an opportunity if the industry type is 'Electronics' and it's working fine but i have a problem with test class so please help out.

Here is the trigger

trigger CreateNewOpportunity on Account (after insert, after update) {
    List<Opportunity> opportunities1 = new List<Opportunity>();
    for(Account acct:Trigger.new){
        if(acct.industry == 'Electronics'){
        Opportunity nopportunity = new Opportunity();
        nopportunity.Name = acct.Name;
        nopportunity.AccountId = acct.Id;
        nopportunity.Amount = 10000;
        nopportunity.StageName = 'Proposal';
        nopportunity.CloseDate = System.today() + 30;

        opportunities1.add(nopportunity);
        }
    }

    if(opportunities1.isEmpty()== false){
       Database.upsert(opportunities1);
    }
}

And here is my Test Class for the same i'm getting only 33% coverage

@isTest
private class opp_test_class {

    static testmethod void test_trigger(){
        account acct = new account(Name = 'sha');
        Opportunity opp = new Opportunity(Name = 'sha',StageName = 'Prospecting',closedate = System.today() + 30);

      //  acct.name = 'sha';
        insert acct;
        insert opp;
    }
}

Best Answer

You need to set the Account's industry field to 'Electronics', because you have a conditional in your trigger that tests for that. So, change your Account record instantiation in your test class to:

account acct = new account(Name = 'sha', Industry = 'Electronics');

You also have to set the AccountId field on the Opportunity prior to inserting the Opportunity, but after inserting the Account.

opp.AccountId = acct.Id
Related Topic