+ Start a Discussion
mba75mba75 

how my test user can be the owner of my test account

 

 

I basically want my user to be the owner of my test account

 

 

 

static testMethod void myUnitTest() { Profile p = [select id from profile where name='Standard User']; User u = new User(alias = 'standt', email='standarduser@testorg.com',isactive=true, emailencodingkey='UTF-8', lastname='Testing', Employee_T_Number__c='111111' , localesidkey='en_AU', profileid = p.Id ,USERROLEID='00E20000000HWRL' , LanguageLocaleKey='en_US',Cost_Centre__c='1236', timezonesidkey='Australia/Sydney', username='standarduser@testorg.com'); Account a=new Account(name='unitest',ownerid=u.id); insert a;

 

apparently the user id is blank . how can I get my user ID ?

 

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
Sadly, this won't work, because you can't have a "User" DML and a non-"User" DML in the same execution chain. There is no way to do this, except to use an existing user that's already in the Database. I've never found a decent way to this in the current version.

All Answers

srisomsrisom

The user id will be blank because you have not inserted it - just created the object.  Try an 'insert u'.  If you are at your full number of users this could fail however - there is not an awful lot you can then do other than selecting back an active user (not as nice as your method of creating one in the test).

 

Good luck, hope this helps.

sfdcfoxsfdcfox
Sadly, this won't work, because you can't have a "User" DML and a non-"User" DML in the same execution chain. There is no way to do this, except to use an existing user that's already in the Database. I've never found a decent way to this in the current version.
This was selected as the best answer
srisomsrisom

    static testMethod void myUnitTest() {
        Profile p = [select id from profile where name='Standard User'];
        User u = new User(alias = 'standt', email='standarduser@testorg.com',isactive=true,
            emailencodingkey='UTF-8', lastname='Testing',
            localesidkey='en_AU', profileid = p.Id , LanguageLocaleKey='en_US',
            timezonesidkey='Australia/Sydney', username='standarduser@testorg.com');
        insert u;
        Account a=new Account(name='unitest',ownerid=u.id, BillingCity='Sydney');
        insert a;
        System.debug(a);

    }   

 

That is straight from my Sandbox.  The debug statement gives:

 

Account:{Name=unitest, BillingCity=Sydney, OwnerId=005R0000000Su6IIAS, Id=001R000000IjGK0IAN}

 

Full coverage of course.  Hope this helps.