1

I'm writing a test class where I need to create an activity with the current user's userid. The test class passes, but no matter what I do Salesforce will not let me upload it. The problem is the user.profileid field.

  1. If I do not include this field in my test class, it tells me this is a required field and I have to have it.

System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [ProfileId]: [ProfileId]

  1. If I make up a fake profile id, it tells me the profile id is invalid.

System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: [] Stack Trace: Class.ActivityHistoryOnProposalTest.getUserId: line 18, column 1

  1. If I set the id to UserInfo.getProfileId(), Salesforce complains that I have a duplicate username.

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.
The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address). : [Username] Stack Trace: Class.ActivityHistoryOnPropertyTest.getUserId: line 20, column 1

There seems to be no way to correctly write this test class.

Class:

public class ActivityHistoryOnProposal{


public String currentUser = UserInfo.getUserId();
public String oldUser;

public String currentP = ApexPages.currentPage().getParameters().get('id');
    public String taskList {get;set;}
    public String soql {get;set;}


    public Task[] getListTasks() {

     oldUser=[select old_ID__c from User where id=:currentUser limit 1]
 [0].old_ID__c;

 taskList = 'select whoid,subject,status, ActivityDate, LastModifiedDate, WhatID, Description, Primary_Contact_Phone_Number__c, Primary_Contact_Email_Address__c, Call_Result__c, Last_Call_Date__c, Last_Call_Agent__c from task WHERE (CreatedbyId=\''+currentUser+'\' OR OLDOWNERID__C=\''+oldUser+'\') AND WhatID =\''+currentP+'\' order by ActivityDate desc limit 20000'; 
 System.debug('~~~~~~'+tasklist);

   //sort out the Listings records
   List<Task> tskList = new List<Task>();
   List<Task> tskListPreSort= Database.query(taskList);

 for (task i:tskListPreSort)
{
if (i.whatid!=NULL){
Id thisId=i.whatid;
String objectAPIName = thisId.getSObjectType().getDescribe().getName();
system.debug(thisId+':'+objectAPIName);
if(objectAPIName=='Proposal__c'){
tskList.add(i);
system.debug(i+' added');
}
else {system.debug('didnt add');}
}
else{system.debug('null');}
}

system.debug('type2:'+tskList);

for (task i:tskList)
{
if (i.whatid!=NULL){
Id thisId=i.whatid;
String objectAPIName = thisId.getSObjectType().getDescribe().getName();
system.debug('2'+thisId+':'+objectAPIName);
}
else{system.debug('null');}
}  




        return tskList;     

}

   public ActivityHistoryOnProposal(ApexPages.StandardController controller){}





}

Test Class:

@IsTest()
public class ActivityHistoryOnProposalTest {

    static testMethod void getUserId() {


        User user = new User();
        user.Alias = 'test';
        user.Email = '[email protected]';
       user.EmailEncodingKey = 'UTF-8';
        user.LastName = 'tester';
        user.LanguageLocaleKey = 'en_US';
        user.LocaleSidKey = 'en_US';
        user.TimeZoneSidKey = 'America/Los_Angeles';
        user.Username = '[email protected]';
        user.IsActive = true;    
        user.profileid=UserInfo.getProfileId();   
        insert user;

        String currentUser = User.id;

        Proposal__c pr=new Proposal__c();

        Task t = new Task();
        t.WhatId=pr.id;
        insert t;



       ApexPages.currentPage().getParameters().put('id', user.old_ID__c);
        Task tsttask = new Task();
        ApexPages.StandardController sc = new ApexPages.StandardController(tsttask); 
        ActivityHistoryOnProposal objActivityHistory = new ActivityHistoryOnProposal(sc); 
        objActivityHistory.getListTasks();
    }
}
1

1 Answer 1

4

The problem is that '[email protected]' is probably taken. You need a unique user name in order to proceed. Here's how I usually create a user name:

user.username = Math.random()+'@'+Math.random();

This will create a user name like '[email protected]', which probably won't collide with any user in any org anywhere (unless someone decides to do this just to spite me).

You can set the ProfileId of the current user (which would usually be a system administrator), or you could query for a specific profile if you need a specific type of user to test with.

3
  • Whoops. I overlooked that obvious mistake.
    – MRG
    Mar 2, 2016 at 0:36
  • 1
    Still a small collision chance there. I prefer static counters, myself. Works pretty well in my test utility. I guess the chance is pretty minuscule when you have random on both sides though.
    – Adrian Larson
    Mar 2, 2016 at 0:42
  • @AdrianLarson The problem has to do with the uniqueness across all orgs. I'm guessing someone's created that user somewhere, probably for testing purposes. Using the random digits that way gives you an approximately 10^30 random permutations that's likely not going to collide with anyone anywhere, even if everyone chose to use this pattern for all unit tests.
    – sfdcfox
    Mar 2, 2016 at 0:50

You must log in to answer this question.

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