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
Andrew ByrnsAndrew Byrns 

Simple Update Trigger Not Covered, Not Sure Why

Seriously, code coverage will be the death of me! This test is not returning any coverage and I can't figure out why. Any suggestions?

Here's the trigger. It's supposed so transfer two dates from the relationship field Opportunity__c on the contract when the contract record is updated. However in the developer console the code coverage is 0%.
 
trigger TransferOpportunityValue on Contract (before update) { 
     
    for(Contract c : Trigger.new){

        if(c.Opportunity__c != null){

        	Opportunity o = [Select id,Pay_History_Received__c,Pay_History_Reviewed__c From Opportunity Where Id = :c.Opportunity__c];
			c.Pay_History_Received__c = o.Pay_History_Received__c;
			c.Pay_History_Reviewed__c = o.Pay_History_Reviewed__c;
            
        }

    }

}

The test class is here, I'm updating the field price_level__c, but to no avail the coverage is still 0% and there are definitely activated contracts. Anyone have any idea why? You help is much appreciated.
 
@isTest

private class TestUpdateContract {
    
    static testMethod void myTest() {

        Contract con; 
        con= [SELECT Id,price_level__c FROM Contract LIMIT 1];
         
        con.price_level__c = '12345';
        update con;           
        
    }

}


 
Best Answer chosen by Andrew Byrns
PavanKPavanK
I believe below code snippt can help for more understanding

@isTest private class TestUpdateContract
{
     static testMethod void myTest()
    {
            Contract con;
            con = new contract();
            //populate required fields
            insert con;
             con.price_level__c = '12345';
             update con;
   }
}

All Answers

PavanKPavanK
Hope you are doing well.

You have to create test data in test method. Once you create data and then you query you will get result from query.

As of now as you are querying data without data creation query is returning zero record and then is no DML operation.

So solution is create data,

There is other way but not best practice, you can enable SeeAllData=true.

Thanks if this reply helped please mark as best response. 
PavanKPavanK
I believe below code snippt can help for more understanding

@isTest private class TestUpdateContract
{
     static testMethod void myTest()
    {
            Contract con;
            con = new contract();
            //populate required fields
            insert con;
             con.price_level__c = '12345';
             update con;
   }
}
This was selected as the best answer
Andrew ByrnsAndrew Byrns
Hi Pawan. Thank you so much for your advice. That did the trick!

 
PavanKPavanK
thanks