1

I am creating a test method to test functionality allowing users to search for other users.

In order to do this, I have tried creating and saving test users with certain criteria, and then searching for those users with a SOQL select. However, when I try to search for those test users, I cannot find them - I only find "real" users that exist outside the test. I assume that this is because "real" users are available to testmethods.

If I cannot rely on "real" users to be consistent between environments, and I cannot create and insert a user within the test, I have no idea how to test this functionality. Is there a way to access users you create & insert within a test method?

1
  • 1
    You can query based off of data that you insert in a test method. The data inserted during the method will be collected and removed at the end of the test. It would help if you posted your code to this as well. Commented Nov 4, 2014 at 14:08

1 Answer 1

3

I don't see why that would not work, I've made a quick example based on what you explained and the test pass perfectly, try it out:

@isTest
private class UserCriteriaFilteringTest {

    @isTest static void user_search_test() {
        // Implement test code
       Profile senior_manager_profile = [select Id, Name from Profile where Name = 'Senior Manager' limit 1];

       Double hash = Double.valueOf(System.now().millisecond());
       User u = new User(alias =  'TestUser',
         email='[email protected]',
         emailencodingkey='UTF-8', lastname='Testing',
         languagelocalekey='en_US', localesidkey='en_US',
         profileid = senior_manager_profile.Id,
         timezonesidkey='America/Los_Angeles', username=  String.valueOf(hash) + '[email protected]');
       insert u;

       hash = Double.valueOf(System.now().millisecond());
       User u1 = new User(alias =  'TestUser',
         email='[email protected]',
         emailencodingkey='UTF-8', lastname='Testing',
         languagelocalekey='en_US', localesidkey='en_US',
         profileid = senior_manager_profile.Id,
        timezonesidkey='America/Los_Angeles', username=  String.valueOf(hash) + '[email protected]');
       insert u1;

       // filter by the email address to get only mock users.
       List<User> users = [select id, Name from User where email = '[email protected]'];

       System.assert(users.size() == 2);

    }


}
1
  • Thank you for the sanity check! I triple-checked the code and found that a trigger was causing the insertion to fail silently in a try-catch block, and because the test class was producing huge debug logs, it was hard to spot. Test users were indeed inserted (and retrieved) fine.
    – Rob
    Commented Nov 5, 2014 at 11:20

You must log in to answer this question.

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