trigger Updaterelatedoppty on Account ( after update,after insert , before insert,before update  ) {

    //before trigger 
    if(Trigger.isbefore )
        for(Account acct :Trigger.new){

            if(Acct.status__c =='Active'){
                Acct.AccountNumber= '123';
                 system.debug('Before '+Acct.AccountNumber);

 //after insert 
 //required fields are mandatory  while creating.

    if(Trigger.isafter && Trigger.isinsert)
   List<Opportunity> opList = New List<Opportunity>();
       for(Account a:Trigger.new)

        if(a.Name != ''  )

            Opportunity o = new opportunity ();
            o.Name = a.Name;
            o.CloseDate = a.enddate__c;
            o.StageName='Closed Won';


        insert opList ;      

 //after update

    if(Trigger.isafter && Trigger.isupdate)  

    set<id> ids = new set<id>();
    List<Opportunity> optyList=new List<Opportunity>();

        for(Account a:Trigger.new)
        if(a.Name !=''  ) 
    for( Opportunity opp : [select id, Description__c,createdby.username from opportunity where  Opportunity.AccountId in: ids ] )


       opp.Description__c= string.valueof(system.now())+string.valueOf(opp.CreatedBy) ;


     update optyList ;


Test class :

@istest public class testtrigger {
    public static @istest void oppTest() {

        Account Acct = new Account();
        Acct.name = 'acc';
        Acct.status__c ='Active';
        Acct.AccountNumber= '123';
       Acct.enddate__c= System.today() ;
       insert Acct;

      Opportunity o =New Opportunity();
            o.Name = Acct.Name;
            o.CloseDate =Acct.enddate__c;
            o.StageName='Closed Won';
            insert o ;

         Opportunity op = [Select id,Description__c ,createdby.username From Opportunity Limit 1 ];

        op.Description__c= string.valueof(system.now())+string.valueOf(op.CreatedBy);
        Update op ;


Am gettting only 59% code coverage.

  • You need to write assertions or your unit test proves nothing about the behavior of your code. This is commonly referred to as a smoke test. – David Reed Jan 29 at 13:13

The quick win for your test class is You need to update the test account which you have inserted in your test method.

if(Trigger.isafter && Trigger.isupdate) will be evaluated true only when you will update the account. Hence you are running short in code coverage. Instead of updating the account, you are updating opportunity.

There are many things you need to consider while writing a test class. Refer here:-

Testing Best Practices

Here is the trailhead you can follow to know more about it:- Get Started with Apex Unit Tests

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.