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
Carlos LabastidaCarlos Labastida 

Error testing trigger on Case..

Hello experts.. Starting on Apex and runnign into some testing trouble.. I wrote a trigger for updating the Last Update time for a Case when a related Task is created: 
trigger updateCaseByTask on Task (before insert) {
    list<id> caseIds = new list<id>();   
    
// Find if this task is related to a Case
    for(Task t : Trigger.new){
       if(string.valueOf(t.whatId).startsWith('500')){
          caseIds.add(t.whatId);
       }
    }
    
// Update Case to refresh Last Update 
    if (caseIds.size() > 0) {
      List<Case> caseList = [SELECT Id FROM Case WHERE Id IN :caseIds];
      update caseList;
    }
}
The trigger is working great. I then wrote a test for it, using an existing test Case I had previously created specificaly for this:
@isTest
public class updateCaseByTaskTest {

    @isTest static void testTaskCreation(){
        Case testCase = [SELECT Id, Subject, Status FROM Case WHERE Subject = 'Case to test updateCaseByTask trigger - DO NOT DELETE' Limit 1];
						

        String caseNumber = testCase.CaseNumber;
        DateTime caseLastModified = testCase.LastModifiedDate;
        Task testTask = new Task();
        // Fill out required Task fields
        testTask.WhatId = testCase.Id;
        testTask.Subject = 'Call';
        testTask.Priority = 'Normal';
        testTask.Status = 'In Progress';
        insert testTask;

        System.assertNotEquals(caseLastModified, testTask.LastModifiedDate);      
    }
}
When I run the query in the Developer's Console Query Editor (
SELECT Id, Subject, Status FROM Case WHERE Subject = 'Case to test updateCaseByTask trigger - DO NOT DELETE' Limit 1), it returns the record, but when the test runs it, it is not finding any result, and giving the error:

System.QueryException: List has no rows for assignment to SObject
Class.updateCaseByTaskTest.testTaskCreation: line 4, column 1


Am I missing anything obvious? Is there a certain format I should write the SOQL on?

Thanks for your help!



Himanshu ParasharHimanshu Parashar
Hi Carlos,

from API Version 27.0 @isTest run with SeeAllData=false which means that org data is not visible inside test class so if you want to run your test method successfully. replace your first line with
 
@isTest(SeeAllData=true)

it will open up your org data for your test method.


P.S. As a test class best practice setting this as true is not recommended, you should create test data inside your test method. you can go through for more details with this link 

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_best_practices.htm


Thanks,
Himanshu