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
Caleb_SidelCaleb_Sidel 

Can you create a customer portal user for the purposes of using it in a testMethod?

UNKNOWN_EXCEPTION, portal account owner must have a role

 

I can not seem to create a customer portal user for my testMethod...has anyone else had success?

 

I really want to runAs() a portal user since the code will be run from there. Currently I'm simply querying for an existing portal user, but that means I have to ensure the same Account/Contact/User are created in every environment including Production and I'd like to avoid having to rely on "dummy" data in Production for my tests to work.

 

I create an account, I create a contact, the account is owned by a user who has a role and profile...but I still get the error above

 

Here is my simplified code (removed personal info, etc) which throws the above error...

 

     static testMethod void Test_getSubjects() {
        Profile pp = [select id from Profile where name LIKE '%Portal%' LIMIT 1];
        Profile sysp = [select id from Profile where name LIKE 'System Administrator' LIMIT 1];
        UserRole r = [select id from UserRole where name = 'CEO' LIMIT 1];
        System.assertNotEquals(null,r);
        User sysU = new User(alias = 'admin',
                    email='admin@testorg.com',
                    emailencodingkey='UTF-8',
                    lastname='Testing',
                    languagelocalekey='en_US',
                    localesidkey='en_US',
                    profileid = sysp.Id,
                    userroleid = r.Id,
                    timezonesidkey='America/Los_Angeles',
                    username='admin@testorg.com');
        insert sysU;
        Account acct = new Account(name='test');
        acct.owner = sysU;
        insert acct;


        User assertUser = [select userroleid from user where id =: acct.ownerId LIMIT 1];

        System.assertNotEquals(null,assertUser.userRoleId);

 

        Contact cont = new Contact();
        cont.lastname = 'test';
        cont.phone = '555-555-5555';
        cont.Account = acct;
        insert cont;
        User u = new User(alias = 'port',
                            email='portaluser@testorg.com',
                            emailencodingkey='UTF-8',
                            lastname='Testing',
                            languagelocalekey='en_US',
                            localesidkey='en_US',
                            profileid = pp.Id,
                            contactid = cont.Id,
                            timezonesidkey='America/Los_Angeles',
                            username='portaluser@testorg.com');
        insert u;
        Test.startTest();
        System.runAs(u) {
            Boolean result = myMethod();

            System.assertEquals(true,result);
        }
        Test.stopTest();
    }

 

Thank you very much. Any and all help is greatly appreciated!

Caleb

richardvrichardv

Hi Caleb, the below code has worked for me in the past.  Also, that error message might be caused by your own username not having a role; so to take that out of the equation, make sure you do have a role.

 

 

private static Integer nextUserSerialNumber = -1;

private static Integer getNextUserSerialNumber(){

nextUserSerialNumber++;

return nextUserSerialNumber;

}

private static List<User> createPartnerUsers(Boolean admin, Integer max, id accountId){

final List<Profile> partnerProfiles = 

[select id,name from Profile where UserType = 'PowerPartner' limit :max];

System.assert(

!(partnerProfiles == null || partnerProfiles.size() <= 0), 

'No partner profiles exist therefore test cannot be executed');

final List<Account> accounts = new List<Account>();

if(accountId == null){

for(Integer i = 0; i < partnerProfiles.size(); i++){

accounts.add(new Account(name='Test ' + i));

}

insert accounts;

for(Account account : accounts){

account.IsPartner = true;

}

update accounts;

}

final List<Contact> contacts = new List<Contact>();

for(Integer i = 0; i < partnerProfiles.size(); i++){

contacts.add(

new Contact(

AccountId=(accountId == null ? accounts.get(i).id : accountId),

Email=''+i+'@xyz.com', 

FirstName = 'John', 

LastName = 'Doe'+i,

Title='VP',

MailingStreet='123 Main',

MailingCity='Peoria',

MailingState='IL',

MailingPostalCode='33333',

Phone='3213213211',

MobilePhone='3213213211',

Fax='3213123211'

)

);

}

insert contacts;

final List<User> users = new List<User>();

for(Integer i = 0; i < partnerProfiles.size(); i++){

Integer userNumber = getNextUserSerialNumber();

users.add(

new User(

Username=''+userNumber+'@xyz.com',

Alias = 'test'+userNumber, 

Email=''+userNumber+'@xyz.com', 

FirstName='John', 

LastName='Doe'+userNumber, 

ProfileId = partnerProfiles.get(i).Id, 

LanguageLocaleKey='en_US', 

LocaleSidKey='en_US', 

EmailEncodingKey='UTF-8', 

TimeZoneSidKey='America/Los_Angeles',

ContactId = contacts.get(i).id

)

);

}

insert users;

return users;

crop1645crop1645

Richardv -- This is very helpful..One question though:

 

You create a Partner Portal user for each outstanding Partner Profile in the org.  Doesn't this require that you have available, unused partner licenses before the testmethod executes?

 

For example, we only have 10 partner portal licenses and they are all in use.  How would one go about creating a partner portal User in a testmethod if the licenses are all used up?

 

Thanks

 

richardvrichardv

Hi Eric,

 

Since i posted the above code, I've re-thought my approach and my new approach should work for you.  Essentially the rule of thumb for unit tests is to "create your own data".  I totally agree with this except in the case of User object.  I (now) believe it's much, much easier to just query for a user and if it's not there, fail the test with a meaningful error message.  Here's an example (note how much simpler this is than the above code):

 


try{
    partner = [select id,name from User where Profile.UserType = 'PowerPartner' and IsActive = true limit 1];
}catch(QueryException e){}
System.assert(partner!=null,'Environment Dependency: no partner users available in your org.  Please create at least one partner user in your org and ensure that user is active.');


 

 

-Richard

Message Edited by richardv on 12-03-2009 07:39 AM