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
erikvmerikvm 

Writing Test Class with SOQL in Trigger?

Hi,

I'm trying to write a test class for my trigger. I tried the trigger in my environment and it works fine, but I can't get the code coverage on the test class, and not really sure how. Here's what the trigger looks like:
trigger AccountTrigger on Account (before insert) {
	list<Account> Acc = [SELECT Id, Name, Generated_ID__c FROM Account WHERE Generated_ID__c != null ORDER BY Generated_ID__c DESC LIMIT 1];
	String Record_ID = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Billing').getRecordTypeId();

    if(Acc.size() > 0){
    	decimal maxLead = Acc[0].Generated_ID__c;
	    for (Account acco : Trigger.new) {
	        if (acco.RecordTypeId == Record_ID) {
	            acco.Generated_ID__c = Integer.valueOf(maxLead)+1;
	            maxLead++;
	        }
	    }
    }
}

And my test class:

@IsTest
private class GenerateExternalIdTest {
    private static String Record_ID = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Billing').getRecordTypeId();

    @isTest static  void createNewAccount() {
        Account newAccount = (Account) TestDataGenerator.createSObject(new Account(RecordTypeId = Record_ID),'TestDataGenerator.AccountDefaults');
        insert newAccount;

    }
}

My issue is that I don't know where to put the query. Right now, the test class code coverage is 37,5% - it skips the actual loop.
 

Thanks in advance!

erikvmerikvm
Essentially, what this trigger does is simply +1 on a field if the Account is a Billing Account.
Paul S.Paul S.
I believe that the code within an if block will only be considered covered if you execute both positive and negative use cases.  Add another test method where the query would return no records and you should find the lines are covered.
Wilfredo Morillo 20Wilfredo Morillo 20
Make sure your testDataGenerator is assigning a value to Generated_ID__c, add this line after the SOQL and make sure the query is returning something,
System.debug(acc);
also you can use this to check if the list is empty:
IF(!Acc.isEmpty()){
}