Question 1
The test method calls an @future method that increments a value. The assertion is failing because the value equals 0. What is the optimal way to fix this?
Java
@isTest
static void testIncrement() {
Account acct = new Account(Name = 'Test', Number_Of_Times_Viewed__c = 0);
insert acct;
AuditUtil.incrementViewed(acct.Id); // This is the @future method
Account acctAfter = [SELECT Number_Of_Times_Viewed__c FROM Account WHERE Id = :acct.Id][0];
System.assertEquals(1, acctAfter.Number_Of_Times_Viewed__c);
}
Asynchronous methods, such as those annotated with @future, do not run immediately when called in Apex. Instead, they are added to a queue to be processed when system resources become available. In a unit test, if you call a future method and immediately query the database for the result, the future method likely hasn't executed yet, resulting in the '0' value observed in the assertion.
To test asynchronous code, you must wrap the call within Test.startTest() and Test.stopTest() (Option D). When the code reaches Test.stopTest(), the execution of the test script pauses, and the system forces all queued asynchronous jobs (future methods, batch jobs, queueable jobs) to run to completion synchronously.
By placing the AuditUtil.incrementViewed(acct.Id) call inside this block, you ensure that by the time the next line of code (the SOQL query) runs, the increment logic has finished and the database reflects the new value. Option B is incorrect because inserting the account is a synchronous operation that doesn't require the stopTest wait. Option A and C avoid the problem rather than testing the logic correctly. Option D is the standard platform-required pattern for testing asynchronous side effects.