I have a batch job with scope as List of User with Id,Name and one Custom field.

Created data in test class with User but as scope getting different user with Name system. Not the which I have created in test class

Batch job scope . start method

query = 'SELECT Id,Name,UserCategory__c from User WHERE IsActive = TRUE LIMIT 1';

Execute method.

for(user u: scope){
    Inventy it =  [select ID from Inventy where  IRole__c = :u.UserCategory__c LIMIT 1];

Getting error

List has no rows for assignment In test class. Created this user for scope.

Integer RandomId1 = Integer.valueOf(Math.rint(Math.random()*1100000)); 
String uniqueName1 = orgId + dateString + RandomId1;
User uu1 = new User(
    firstname = 'ABC', 
    lastName = 'XYZ', 
    Isactive = true,
    email = uniqueName1 + '@test' + orgId + '.org', 
    Username = uniqueName1 + '@test' + orgId + '.org', 
    EmailEncodingKey = 'ISO-8859-1', 
    Alias = uniqueName1.substring(18, 23), 
    TimeZoneSidKey = 'America/Los_Angeles', 
    LocaleSidKey = 'en_US', 
    LanguageLocaleKey = 'en_US', 
    ProfileId = pf.Id,
    UserCategory__c = 'Junior'        

But still while debuggig saw that this user is not considered in scope. Instead of this different user created with Name System.

1 Answer 1


There is Database Isolation in Unit Tests, but users are not hidden from unit tests this way. You can always query real users in unit tests. If you want to make sure you get the user you created, you should include an ORDER BY clause:

query = 'SELECT Id,Name,UserCategory__c from User WHERE IsActive = TRUE ORDER BY CreatedDate DESC LIMIT 1';
  • It worked. now getting user which i created in test class. Thank you
    – SAK
    Oct 19, 2021 at 12:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .