0

I have a class that I have been running without any issues. I've created a test class to get a bit of code coverage for it and the test is failing when the constructor is called.

Without going into too much detail about the underlying class, I wanted to see why the code would run fine via Execute Anonymous but cause an error via the test unit.

Execute Anonymous (runs fine):

authClass auth = new authClass();
auth.login();
system.assert(auth.getSession_id() == null);
String session = auth.getSession_id();
system.assert(session != null);
auth.logout();

Test Class (error when authClass contructor is called):

@isTest
public class authClass {
    static testMethod void testLogIn(){
        authClass auth = new authClass();
        auth.login();
        system.assert(auth.getSession_id() == null);
        String session = auth.getSession_id();
        system.assert(session != null);
        auth.logout();
    }
}

A bit of background... the constructor for authClass queries a Custom Setting and populates private variables in the class. Everything works fine from Execute Anonymous or when I call this authClass from another class. Very confused...

2

Unit tests, by default, run in isolation mode (at least since version 28). This means that most live data will not appear in your unit test, including custom settings. Most likely, your code is assuming custom settings do exist, which means that the code is legitimately crashing. The easiest way to fix this is to add some custom settings to your unit test:

insert new CustomSetting__c(Name='SomeValue', Custom1__c=1234, Custom2__c='Foo Bar');
3
  • Ah, brilliant! That is what I was leaning towards, but am new to unit testing in Apex. Thanks for the eloquent explanation! Makes perfects sense now! – Geoffrey Penny Jan 13 '16 at 16:25
  • This works, but now I am unable to run a Web Service Callout in a subsequent call. auth.login() calls out another API. Any idea how to workaround this? the future method complicates things a bit as the class maintains a session for other API calls like auth.logout(). – Geoffrey Penny Jan 13 '16 at 21:36
  • Nevermind! Answered my own question. developer.salesforce.com/docs/atlas.en-us.198.0.apexcode.meta/… – Geoffrey Penny Jan 13 '16 at 22:15

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.