0

I have written a TestClass for a trigger which basically throws an exception if more than the specified number of incidents are opened for a single user at any given point of time.I am also creating the user in my TestClass using a future method to avoid mixed dml exception. Below is my code-

    @isTest
public class IncidentLimit_Test {
    public static testmethod void testcountincident(){
        string profileid = (String)[SELECT Id FROM Profile WHERE Name='Standard User'].id;

        User usr = CreateUser('Ben','testname',profileid);
          List<Incident__c> inclist = new List<Incident__c>();   
        System.runAs(usr){
            Test.startTest();

            for(integer i=1;i<=5;i++)
            {
              inclist.add(new Incident__c(client__c=usr.id,Description__c='incident'+i));
            }
           insert inclist;
        Test.stopTest();
        }
        System.assertEquals(5, inclist.size());
    }

public static UserRole CreateUserRole(String name) {
    UserRole ur = new UserRole();
    ur.Name = name;
    return ur;
}


    public static User CreateUser(String firstname, String lastname, String profileId) {
    UserRole ur = CreateUserRole('Testing');
    User usr = new User(FirstName = firstname,
                        LastName = lastname,
                        Username = firstname + '.' + lastname + '@testing.com',
                        IsActive = true,
                        UserRoleId = ur.Id,
                        Email = 'testuser@testing.com', 
                        Alias = 'tusr', 
                        TimeZoneSidKey = 'Europe/Berlin' , 
                        LocaleSidKey = 'en_US', 
                        EmailEncodingKey = 'UTF-8', 
                        ProfileId = profileId, 
                        LanguageLocaleKey = 'en_US'
                        );
    return usr;
}
}

My TestClass fails to execute until I annotate it with (seealldata=true).If I am not wrong the only live data I am accessing here is context user's id. UserInfo class belongs to system namespace. Why does test context don't have access to system data?

1

I believe user data is accessible, although I have no idea what may cause you problem I will try help you with your code.

This :

User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()]; System.runAs(thisUser) {

is pointless. I even think it may cause some distraction, as you change context from current user to current user...

Creating user in test should not be done in future method - its just wasting of resources (Test.startTest()/Test.stopTest()). If there are any problems with this - investigate and fix, because there is some bug.

Testing - judging by your code there is unhandled exception in trigger, handle it and check number of successfully inserted records instead of exception text.

Try something like this(it is not working code) :

@isTest(seeAllData=true)
public class IncidentLimit_Test {

public static testmethod void testcountincident(){ 

    User usr = CreateUser('Some firstName','Some lastName', 'some profile Id collected by other methode ');
    insert usr;

    System.runAs(thisUser) {
        Test.startTest();
            List<Incident__c> inclist = new List<Incident__c>();
            for(integer i=1;i<=5;i++)
            {
              inclist.add(new Incident__c(client__c=u.id,Description__c='incident'+i));
            }
           insert inclist;
        Test.stopTest();
        }

        // assert here    }

public static UserRole CreateUserRole(String name) {
    UserRole ur = new UserRole();
    ur.Name = name;
    return ur;
}

public static User CreateUser(String firstname, String lastname, String profileId) {
    UserRole ur = CreateUserRole('Testing');
    User usr = new User(FirstName = firstname,
                        LastName = lastname,
                        Username = firstname + '.' + lastname + '@testing.com',
                        IsActive = true,
                        UserRoleId = ur.Id,
                        Email = 'testuser@testing.com', 
                        Alias = 'tusr', 
                        TimeZoneSidKey = 'Europe/Berlin' , 
                        LocaleSidKey = 'en_US', 
                        EmailEncodingKey = 'UTF-8', 
                        ProfileId = profileId, 
                        LanguageLocaleKey = 'en_US'
                        );
    return usr;
}
|improve this answer|||||
  • Artur, don't you think will receive a MIXED_DML_EXCEPTION if both User & Incidents are inserted in one call. – Jarvis Jan 24 '15 at 16:29
  • 1
    @Bennie - If you wrap code in run as and run it as the user that was just inserted, you will NOT get MixedDML message. You do all the setup objects as the running user, then test the code as the user you created using runAs – Eric Jan 25 '15 at 4:44
  • @Artur Do I have to define a method for collecting the profile id by creating some test profile just like you did for userrole? Can't I do a SOQL query to use existing profiles in the system? Something like string profileid = (String)[SELECT Id FROM Profile WHERE Name='Standard User'].id; User usr = CreateUser('Ben','Bentaleb',profileid); – Jarvis Jan 28 '15 at 3:16
  • FYI you do NOT need to insert a User before passing them into system.runAs, though the record does have to be ready for insert. – Adrian Larson Jan 28 '15 at 5:38
  • 1
    I think you misunderstand what I was saying. You should make the User record in your test that you reference in system.runAs, but you do not need the record to be inserted before calling system.runAs on it. The method does part for you. – Adrian Larson Jan 28 '15 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.