When I run this code from within a LWC controller:

ApexPages.PageReference pageRef = Site.login(username, password, url);

It returns a valid PageReference instance.

But when I test the code in a Apex Test class, the variable pageRef is always null

Here is my controller Apex class:

public classs CustomerSignupController {

    public static String createAccount(SignupParams params) {

        // create user, account and portal user etc

        ApexPages.PageReference pageRef = Site.login(email, password, null);

        if (pageRef == null) {
            return null;
        return pageRef.getUrl();

Here is my Apex test code:

// arrange
String response;
Test.setCurrentPage(new PageReference('/customer/s/signup'));

// act
System.runAs(u) {
    response = CustomerSignupController.createAccount(params);

// assert
System.assertNotEquals(null, response);

I am running the code within the User context of the Portal Site Guest User

And, I've tried setting Test.setCurrentPage but it does not make any difference, but perhaps I am not creating the PageReference correctly?

NOTE: please do not provide solutions that involve polluting my production code with:

if (Test.isRunningTest()) { ... }

I'd to like to understand how I can use Test.setCurrentPage when testing an LWC component's apex controller to work around the issue and test the code correctly.


  1. What am I doing wrong?
  2. How can I make Site.login return a valid PageReference from within a test?
  • Can you see the json value of pagereference and set the same JSON(kind of mocking part). So that assertion will be proper. You can make this pagereference as testvisible so that you can test both ways, null and valid way. – Ysr Shk Aug 11 '20 at 13:39
  • @YsrShk - do you have an example of this approach? – Robs Aug 12 '20 at 11:16
  • for site.login no. I typically use JSON to set the object. Like we used to set the pastdated createdDate by using JSON. – Ysr Shk Aug 12 '20 at 14:31

Your Answer

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

Browse other questions tagged or ask your own question.