1

I am having issues getting test coverage for my redirect method within my controller. The error I keep getting is "System.QueryException: List has no rows for assignment to SObject" located where I am query for the user in the Visualforce page. I understand that the error can't find a matching record in the database. From what I read, I need to initialize the user? I'm just confused because it works in my dev environment, so it seems to know which User to grab, it's just this darn test method doesn't want to cooperate. Any help would be great, thanks.

Visualforce

<apex:page controller="FreezeUser">
    <script type="text/javascript">
    var __sfdcSessionId = '{!GETSESSIONID()}';
    </script>

    <script src="../../soap/ajax/29.0/connection.js"
       type="text/javascript"></script>

    <script type="text/javascript">     

    function getUserInfo(){
      var userInfoById = {};

      var result = sforce.connection.query("Select Id, UserId, IsFrozen, IsPasswordLocked From UserLogin order by UserId");

      var it = new sforce.QueryResultIterator(result);

      while(it.hasNext()){
         var record = it.next();

         userInfoById[record.UserId] = record;
      }  

      var output='<table><td><b>User<b></td><td></td><td></td><td><b>Action<b></td>';

      var selectedUser = "'{!u.Id}'";
      result = sforce.connection.query("SELECT Id, FirstName, LastName, isActive from User where Id = " + selectedUser);

      it = new sforce.QueryResultIterator(result);

      while(it.hasNext()){
        var record = it.next();

        if (record.Id in userInfoById){
          var userInfo=userInfoById[record.Id];
          var name=record.FirstName + ' ' + record.LastName;
            output+='<tr><td>' + name + '</td><td>';
          if (userInfo.IsFrozen=='true'){
            output+="<td><button onclick=\"unfreeze('" + userInfo.Id + "', '" + name + "', false);\">Unfreeze</button>";
          } else {
            output+="<button onclick=\"freeze('" + userInfo.Id + "', '" + name + "', true);\">Freeze</button>";
          }
          output+='</td></tr>';

        }
      }

      output+='</table>';

      document.getElementById('output').innerHTML=output;
    }

  function freeze(Id, name, freezerState){
    alert("Freezing " + name);
    var userlogin = new sforce.SObject("UserLogin");
    userlogin.Id = Id;
    userlogin.IsFrozen = freezerState;
    var result = sforce.connection.update([userlogin]);

    if (result[0].getBoolean("success")) {
        console.log(name + " " + (freezerState?'frozen':'unfrozen'));
    } else {
        console.log("failed to freeze " + name + " " + result[0]);
    } 

    window.location.reload();
  }

  function unfreeze(Id, name, freezerState){
    alert("Unfreezing " + name);
    var userlogin = new sforce.SObject("UserLogin");
    userlogin.Id = Id;
    userlogin.IsFrozen = freezerState;
    var result = sforce.connection.update([userlogin]);

    if (result[0].getBoolean("success")) {
        console.log(name + " " + (freezerState?'unfrozen':'frozen'));
    } else {
        console.log("failed to unfreeze " + name + " " + result[0]);
    } 

    window.location.reload();
  }

  </script>

  <apex:pageMessages />
  <apex:form > 

    <apex:pageBlock title="Freeze/Unfreeze User" rendered="{!IF(u.id != null, true, false)}">

        <apex:pageBlockSection >
          <apex:pageBlockSectionItem >
              <div id="output"></div>
          </apex:pageBlockSectionItem>
        </apex:pageBlockSection>

    </apex:pageBlock>

    <apex:commandButton id="back" action="{!redirect}" value="Back to User" rendered="{!IF(u.id != null, true, false)}"/>

  </apex:form> 

  <script>
    getUserInfo();
  </script>


</apex:page>

Controller

public with sharing class FreezeUser {

    public User u { get; set; }

    public FreezeUser(){
        User u = [SELECT Id FROM User WHERE Id = :ApexPages.currentPage().getParameters().get('Id') Limit 1];
    }

    public PageReference redirect(){
        PageReference redirectUser = new PageReference('/' + u.Id);
        redirectUser.setRedirect(true);
        return redirectUser;
    }

}

Test Class

@isTest
public class FreezeUser_Test {

    public static testMethod void validateUser(){
        Profile p = [SELECT id FROM Profile WHERE Name='Standard User'];

        User u = new User(
            FirstName = 'test', 
            LastName= 'last_test', 
            Email='[email protected]', 
            Phone='111-111-1111', 
            True_Market_Unit__c='1111', 
            alias = 'test', 
            EmailEncodingKey='UTF-8',
            ProfileId = p.Id,
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US', 
            TimeZoneSidKey='America/Los_Angeles',
            UserName = '[email protected]'
        );

        insert u;

        System.assertEquals('test', u.FirstName);
    }

    public static testMethod void testRedirect(){

        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];

        User u = new User(
            FirstName = 'test', 
            LastName= 'last_test', 
            Email='[email protected]', 
            Phone='111-111-1111', 
            True_Market_Unit__c='1111', 
            alias = 'test', 
            EmailEncodingKey='UTF-8',
            ProfileId = p.Id,
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US', 
            TimeZoneSidKey='America/Los_Angeles',
            UserName = '[email protected]'
        );

        try{
            insert u;
        }catch(DMLException e){
            System.debug('Error inserting new user: ' + e.getMessage());
        }

        System.runAs(u){
            FreezeUser obj = new FreezeUser();
            PageReference pageRef = obj.redirect();

            System.assertNotEquals(null, pageRef);
            //System.assertEquals('/apex/freezeUser', pageRef.getUrl());
            System.assertEquals('/' + u.Id, pageRef.getURL());
        }

    }

}
1
  • Try adding ApexPages.currentPage().getParameters().put('Id',u.id); before initializing obj. Commented Jun 23, 2015 at 18:02

1 Answer 1

1

You forgot to put the "ID" parameter into the page's parameters. Sometime before you call new FreezeUser(), you need to set the parameter:

Test.setCurrentPage(Page.freezeUser);
ApexPages.currentPage().getParameters().put('Id', u.Id);

You must log in to answer this question.

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