+ Start a Discussion
Terry411Terry411 

Test class users

Can some tell me what I'm missing in this snippet of code from my test class?  I'm creating two user records to use through the test class.  I recieve a System.QueryException: List has no rows for assignment to SObject on the last line of the code. 

 

 

		Profile p = [SELECT Id FROM profile WHERE name='System Administrator'];  
		
		User u1 = new User(alias = 'newUser1', email='newuser1@testorg.com',  
					emailencodingkey='UTF-8', lastname='Testing1',   
					languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id,  
					timezonesidkey='America/Chicago', username='newuser1@testorg.com');  
		
		User u2 = new User(alias = 'newUser2', email='newuser2@testorg.com',  
					emailencodingkey='UTF-8', lastname='Testing2',   
					languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id,  
					timezonesidkey='America/Chicago', username='newuser2@testorg.com');  
		
		System.runAs(u1) {
			// Get Test User Id
			Id UserId = [Select Id From User where username = 'newuser1@testorg.com'].Id ;
			Id NewOwnerId = [Select Id From User where username = 'newuser2@testorg.com'].Id ;

 

 

sravusravu

Try this way of inserting users and see :

 

User u1 = new User();
u1.alias = 'newUser1';
u1.email='newuser1@testorg.com';
u1.emailencodingkey='UTF-8';
u1.lastname='Testing1';
u1.languagelocalekey='en_US';
u1.localesidkey='en_US';
u1.profileid = p.Id;
u1.timezonesidkey='America/Chicago';
u1.username='newuser1@testorg.com';
insert u1;  
        
        User u2 = new User();
        u2.alias = 'newUser2';
        u2.email='newuser2@testorg.com';
        u2.emailencodingkey='UTF-8';
        u2.lastname='Testing2';
        u2.languagelocalekey='en_US';
        u2.localesidkey='en_US';
        u2.profileid = p.Id;
        u2.timezonesidkey='America/Chicago';
        u2.username='newuser2@testorg.com';
        insert u2;

 

Try to use @isTest in your test class and declare the class as private

 

Please let me know if you face any difficulty.

jaganjagan

After declare statements ....try inserting them before the system.runAs(u1) statement....like insert u1; and insert u2;

 

Hope this will solve your problem !!

 

Thanks,

Jagan.

Terry411Terry411
User[] u = new User[] {u1, u2};
insert u;

 

This approach worked.  Not sure why I didn't do that from the beginning.  Thanks guys