2

Can anyone tell me why this test is true? It should be false, but it is true.

If I run this query I get the data that I expect:

SELECT PrivateIncInfo__APIAuthorizationKey__c from PrivateIncInfo__SameDaySession__c  where PrivateIncInfo__User_Id__c=:thisUserId ORDER BY CreatedDate desc LIMIT 1

I fill in an actual userid, which I got from a System.debug () statement.

This is the code:

public static PrivateIncInfo__SameDaySession__c findCurrentSession() {
PrivateIncInfo__SameDaySession__c ps = new PrivateIncInfo__SameDaySession__c(); 


    // 2017-06-21 -- I'm pulling out the userid stuff to its own line so I can test this method from the
    // the unit tests. In the unit tests there won't be a user, so we will simply return the last session.
    String thisUserId = userinfo.getuserid();

    System.debug('thisUserId'); 
    System.debug(thisUserId); 

    List<PrivateIncInfo__SameDaySession__c> SameDaySessions = new List<PrivateIncInfo__SameDaySession__c>();

    if (thisUserId != null) {


        System.debug('so we will get the sessions via the userid'); 

        // 2017-04-17 -- 
        // see: https://developer.salesforce.com/forums/?id=906F0000000906dIAA
        SameDaySessions = [SELECT PrivateIncInfo__APIAuthorizationKey__c from PrivateIncInfo__SameDaySession__c  where PrivateIncInfo__User_Id__c=:thisUserId ORDER BY CreatedDate desc LIMIT 1];

    } else {

        System.debug('so we will get the sessions via NO userid'); 
        SameDaySessions = [SELECT PrivateIncInfo__APIAuthorizationKey__c  FROM PrivateIncInfo__SameDaySession__c ORDER BY CreatedDate desc LIMIT 1];

    }

if (SameDaySessions == null) {
    System.debug('Error: in SameDaySessionModel no user session detected. SameDaySessions was null.'); 
} else if (SameDaySessions.size() == 0) {
    System.debug('Error: in SameDaySessionModel SameDaySessions.size() equaled zero..'); 
} else {
    ps = SameDaySessions[0];
}

return ps;
}

This is the test:

@isTest
static  void testFindCurrentSession(){
    // Generate test model
    PrivateIncInfo__SameDaySession__c currentSameDaySession = SameDaySessionModel.findCurrentSession();


    // Perform test logic
    Test.startTest();


    Boolean authKeyIsNull = false; 

    if (currentSameDaySession.PrivateIncInfo__APIAuthorizationKey__c == null) {
        authKeyIsNull = true; 
    } 


    Test.stopTest();        


    // Assert logic
    //
    // 2017-06-21 - the automated security test at Salesforce complained that I had not added an assert statement here
    // so I'm now adding the most obvious thing that I can think of. 
    //
    System.assertEquals(true, authKeyIsNull, 'When we call SameDaySessionModel.findCurrentSession() we expect to get back an instance of PrivateIncInfo__SameDaySession__c with a PrivateIncInfo__APIAuthorizationKey__c that is not null.');
}

authKeyIsNull is always true, meaning this is always false:

currentSameDaySession.PrivateIncInfo__APIAuthorizationKey__c

but that should be impossible. When I run the query myself, I see the data in the query editor.

So why would the value come back null from Salesforce?

In the log for the when I run the unit test, I see this:

21:33:00:000 LIMIT_USAGE_FOR_NS Number of SOQL queries: 1 out of 100

That implies that a SOQL query is run. But it comes back empty?

3

Both posted answers about isolated test data are accurate. To connect the dots for you, here is your code with the missing bits added along with an appropriate assertion in the test.

Don't use seeAllData=true unless it's your only option, such as with Pricebook records.

@isTest
static  void testFindCurrentSession(){
    // create and insert a user
    User u = new User(
        FirstName           = 'Test',
        LastName            = 'User ',
        Email               = 'email@example.12345123456',
        Username            = 'email@example.12345123456',
        Alias               = 'tuser987',
        Phone               = '123-555-1212',
        ProfileId           = 'yourProfileId',
        TimeZoneSidKey      = 'America/Los_Angeles',
        LocaleSidKey        = 'en_US',
        EmailEncodingKey    = 'ISO-8859-1',
        LanguageLocaleKey   = 'en_US'
    );

    insert u;

    // create test data for the isolated test
    PrivateIncInfo__SameDaySession__c recordToInsert = new PrivateIncInfo__SameDaySession__c();
    recordToInsert.PrivateIncInfo__APIAuthorizationKey__c = 'yourAPIkeyValue';
    recordToInsert.PrivateIncInfo__User_Id__c = u.Id;

    insert recordToInsert;


    // wrap the test with a runas(user) to ensure that the results are correct for this specific user
    system.runas(u) {

        // Perform test logic
        Test.startTest();

        // Generate test model
        PrivateIncInfo__SameDaySession__c currentSameDaySession = SameDaySessionModel.findCurrentSession();

        // ensure that the code returned the expected value for the auth key
        System.assertEquals('yourAPIkeyValue', currentSameDaySession.PrivateIncInfo__APIAuthorizationKey__c, 'The authorization key was not the expected value.');

        Test.stopTest();        
    }
}
2

You need to create test data to satisfy SOQL query, otherwise you have use @seeAllData=true so that you could see organization data which is not recommended unless it is absolutely necessary.

2

If you want to see live data in your tests, you'll need to add the SeeAllData Annotation:

@isTest(SeeAllData=true)

However, this is generally not recommended because it tightly couples your test method to actual data in the org, which can make it more difficult to deploy your test methods. Instead, you can insert data in your test method, and it will be visible to your test, but not persist in the database once your test is completed (minor note - it will increase auto numbers).

Usually, I only use the SeeAllData annotation if there is an object which must have specific records in it for the app itself to function - the main example of this would be records containing some form of meta-data - and that that data must be configured in a precise way which would be easy to mess up. Even then, you should carefully consider whether adding the annotation increases the maintenance of your test class too much to be worth it.

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.