The prebuilt class LightningLoginFormController has a try/catch block that I am trying to cover in test.
@AuraEnabled
public static String login(String username, String password, String startUrl) {
try{
ApexPages.PageReference lgn = Site.login(username, password, startUrl);
aura.redirect(lgn);
return null;
}
catch (Exception ex) {
return ex.getMessage();
}
}
I am having trouble getting the login to throw an exception. My current test code is:
try {
String newRes = LightningLoginFormController.login(null, null, null);
system.debug('New Result is ' +newRes);
} catch (DmlException ex) {
System.assertEquals('expected text', ex.getMessage());
}
}
But all it does is return null. Any ideas on how I get the Login method to throw an exception?
My new code, based on @Adrian Larson suggestion is now as follows:
Class
global class LightningLoginFormController {
<… other code that is already covered …>
@AuraEnabled
public static String login(String username, String password, String startUrl) {
try{
ApexPages.PageReference lgn = Site.login(username, password, startUrl);
aura.redirect(lgn);
return null;
}
catch (Exception ex) {
return ex.getMessage();
}
}
static LoginService service = new LoginService();
@TestVisible static void setMock(LoginService mock) { service = mock; }
public virtual class LoginService
{
protected virtual ApexPages.PageReference login(String username, String password, String startUrl)
{
return Site.login(username, password, startUrl);
}
}
}
Test Class
@IsTest
public without sharing class LightningLoginFormControllerTest {
<… other code that already works …>
@IsTest static void testLogin()
{
LightningLoginFormController.setMock(new MyMock());
Test.startTest();
LightningLoginFormController.login('testUser', 'fakepwd', null);
Test.stopTest();
system.assertEquals(null, 'Exception',
'The exception should be caught');
}
class MyMock extends LightningLoginFormController.LoginService
{
protected override ApexPages.PageReference login
(String username, String password, String startUrl)
{
throw new DmlException();
}
}
}
The problem is the Catch block is still not getting caught and some of the additional code (the public virtual class LoginService method) is not being caught either.