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
Melissa BunchMelissa Bunch 

List has no rows for assignment to SObject Apex Text Class Error

Hello!
I have an unmanaged package installed that I am pushing a change for.
Upon validation, I am receiving the following error in production (repeated for each test line):


System.QueryException: List has no rows for assignment to SObject
Stack Trace: Class.CaseStatusChangeTriggerHandlerTest.getUser: line 139, column 1 Class.CaseStatusChangeTriggerHandlerTest.testAccessible1: line 66, column 1

Below is the full code for the test class.
Does anyone know of a way I could rewrite the @istest lines so that they don't fail when they don't find a user? I put the line in bold below that the above error references.

@IsTest
public class CaseStatusChangeTriggerHandlerTest {

    @testSetup static void setupTestdata() {
        
        Case newCase = new Case();
        newCase.Subject = 'Unittest';
        newCase.Status = 'New';
        insert newCase; 
        
        Case testCase = [select Subject, Status from Case where Subject = 'Unittest']; 
        System.assertEquals(testCase.Subject, 'Unittest');
    }
        
    @IsTest static void testOnAfterInsert(){

        Case[] testCase = [select Subject, CaseNumber, Status, Owner.Name from Case where Subject = 'Unittest'];
        
        CaseStatusChangeTriggerHandler.OnAfterInsert(testCase);
        
        Case_Status_Change__c[] caseStatusChange = [select Name from Case_Status_Change__c where Case__r.Id =:testCase[0].Id];
        
        System.assertEquals(caseStatusChange[0].Name, testCase[0].CaseNumber + ' status: New');    
    }        
    @IsTest static void testOnAfterUpdate(){

        Map<Id, Case> oldObjectMap = new Map<Id, Case>();
          
        Case[] testCase = [select Subject, CaseNumber, Status, Owner.Name from Case where Subject = 'Unittest'];
        
        Case_Status_Change__c  statusChange = new  Case_Status_Change__c();
        statusChange.Name = testCase[0].CaseNumber + ' status: New';
        statusChange.Case__c = testCase[0].Id;
        statusChange.Status_Name__c = testCase[0].Status;
        statusChange.Set_Time__c = Datetime.now();
        insert statusChange;
        
        testCase[0].Status = 'Escalated';

        Case oldCase = new Case();
        oldCase.Subject ='Unittest';
        oldCase.Status = 'New';
        oldCase.Id=testCase[0].Id;
        oldObjectMap.put(testCase[0].Id, oldCase);
        
        CaseStatusChangeTriggerHandler.OnAfterUpdate(testCase, oldObjectMap);
        
        Case_Status_Change__c[] caseStatusChange = [select Name from Case_Status_Change__c where Case__r.Id=:testCase[0].Id and Change_Time__c = null];        
        System.assertEquals(caseStatusChange[0].Name, testCase[0].CaseNumber + ' from New to Escalated');    
    }     
    /**
     *Tests if the user does not have access to Case and Case_Status_Change__c objects
     */
    @IsTest static void testAccessible1(){
       
        User u = getUser('NotAccessible1');

        System.runAs(u) {
            try {
                testOnAfterInsert();
                System.assert(false, 'fail the test if no exception thrown ');
            }
            catch (QueryException e) {
                 System.assertEquals(e.getMessage(), 'Insufficient access to Case or User objects');         
            }   
        }  
    }    

    @IsTest static void testAccessible2(){
        
        User u = getUser('NotAccessible2');
        
        System.runAs(u) {
            try {
                testOnAfterUpdate();
                System.assert(false, 'fail the test if no exception thrown ');
            }
            catch (QueryException e) {
                 System.assertEquals(e.getMessage(), 'Insufficient access to Case Status Change or business hours objects');         
            }   
        }
    }    
    @IsTest static void testCreatable(){
        
        User u = getUser('NotCreatable');
        
        System.runAs(u) {
            try {
                testOnAfterInsert();
                System.assert(false, 'fail the test if no exception thrown ');
            }
            catch (DmlException e) {
                 System.assertEquals(e.getMessage(), 'Insufficient permissions to create Case Status Change');         
            }    
        }        
        System.runAs(u) {
            try {
                testOnAfterUpdate();
                System.assert(false, 'fail the test if no exception thrown ');
            }
            catch (DmlException e) {
                 System.assertEquals(e.getMessage(), 'Insufficient permissions to create Case Status Change');         
            }    
        }     
    }    
    @IsTest static void testUpdatable(){
        
        User u = getUser('NotUpdatable');
        
        System.runAs(u) {
            try {
                testOnAfterUpdate();
                System.assert(false, 'fail the test if no exception thrown ');
            }
            catch (DmlException e) {
                 System.assertEquals(e.getMessage(), 'Insufficient permissions to update Case Status Change');         
            }
            
        }      
    }    
    public static User getUser(String profileName) {
        
        Profile p = [SELECT Id FROM Profile WHERE Name=:profileName limit 1];
        
        String testemail = 'atest@test.demo';
        User pu = new User(profileId = p.Id, username = testemail, email = testemail, 
                           emailencodingkey = 'UTF-8', localesidkey = 'en_US', 
                           languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles', 
                           alias='cspu', lastname='lastname');        
        return pu;
       
    }  
}
Abdul KhatriAbdul Khatri
Hi Melissa,

Looks like the profileName you are passing do not exists in your Org. Please make sure the profile name you are passing exists. The following line is failing in that getUser method. Profiles are visible in test class, you should use the one available, against which you are testing your code.
 
Profile p = [SELECT Id FROM Profile WHERE Name=:profileName limit 1];
If you still wanted to use this scenario, then the following is a way to handle it but I would anticipate unexpected test results.
 
    public static User getUser(String profileName) {
        List<Profile> pList = [SELECT Id FROM Profile WHERE Name=:profileName];
        
        if (pList == null OR pList.isEmpty()) return null;

        String testemail = 'atest@test.demo';
        User pu = new User(profileId = pList[0].Id, username = testemail, email = testemail, 
                           emailencodingkey = 'UTF-8', localesidkey = 'en_US', 
                           languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles', 
                           alias='cspu', lastname='lastname');        
        return pu;
   }
I would recommend to verify your profile you are using in the test class.

Regards.

 
mukesh guptamukesh gupta
Hi Mellisa,

Always try to use Test class best practices in for your code you need to use asserEquels(), this will not allow if you are worng,

So use below  line of code in each method 


String profileName = 'NotAccessible1'

Profile p = [SELECT Id,Name FROM Profile WHERE Name=:profileName limit 1];
System.assertEquals(p.Name,profileName);

After that use below code 
 
public static User getUser(String profileName) {
        List<Profile> pList = [SELECT Id FROM Profile WHERE Name=:profileName];
        
        if (pList == null OR pList.isEmpty()) return null;

        String testemail = 'test@gmail.com';
      User u = new User( ProfileId = pList[0].Id, LastName = 'last', Email = 'puser000@amamama.com', Username = 'puser000@amamama.com' + System.currentTimeMillis(), CompanyName = 'TEST', Title = 'title', Alias = 'alias', TimeZoneSidKey = 'America/Los_Angeles', EmailEncodingKey = 'UTF-8', LanguageLocaleKey = 'en_US', LocaleSidKey = 'en_US');
        return u;
   }

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh 
Melissa BunchMelissa Bunch
Thank you both!
When I am trying to update the profile section, I am getting this error and cannot save:

Error: Compile Error: Expecting ')' but was: 'OR' at line 141 column 27

Here is how it's written:

   public static User getUser(String profileName) {
        
 List<Profile> pList = [SELECT Id FROM Profile WHERE Name=:profileName];
        
        if (pList == null OR pList.isEmpty()) return null;

        String testemail = 'atest@test.demo';
        User pu = new User(profileId = pList[0].Id, username = testemail, email = testemail, 
                           emailencodingkey = 'UTF-8', localesidkey = 'en_US', 
                           languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles', 
                           alias='cspu', lastname='lastname');        
        return pu;
   }


I apologize for my ignorance, so any advice would be great!

Thank you
Abdul KhatriAbdul Khatri
Hi Melissa,

Sorry there is not such thing OR in condition check instead it is represented like II so change you code to this
 
public static User getUser(String profileName) {
        
 	List<Profile> pList = [SELECT Id FROM Profile WHERE Name=:profileName];
        
        if (pList == null || pList.isEmpty()) return null;

        String testemail = 'atest@test.demo';
        User pu = new User(profileId = pList[0].Id, username = testemail, email = testemail, 
                           emailencodingkey = 'UTF-8', localesidkey = 'en_US', 
                           languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles', 
                           alias='cspu', lastname='lastname');        
        return pu;
   }

I hope this will help address your issue. 

Regards.