Our class code looks like this:       String userId = Site.createPortalUser(u, accountId, password);     if (userId != null) {          if (password != null &amp;&amp; password.length() &gt; 1) {             return Site.login(username, password, null);         }         else {             PageReference page = System.Page.SiteRegisterConfirm;             page.setRedirect(true);             return page;         }     }   Site.createPortalUser always returns false while running test class. How can we cover code under if(userId != null) ?
121434
I have a siteRegistrationController which is creating portal users as below:  Registration Controller:  public class SiteRegistrationController{      public void createPortalUser(){         //There is code to populate the values for variables u and acc.         String userId = Site.createPortalUser(u, acc.Id,null,false);             System.debug('userId is '+userId);     }  }   I am trying to test the above code and below is in my test class:  Test Class:  public class SiteRegistrationController_TEST{          SiteRegistrationController controllerObj = new SiteRegistrationController();          User guestUserObj = new User(username='testsfsdfsd@test.com',                                 IsActive=TRUE,                                 FirstName='test',                                 LastName='test',                                 Email='testsdfsd@test.com',                                 Alias='test',                                 timezonesidkey='America/Los_Angeles',                                 localesidkey='en_US',                                 emailencodingkey='UTF-8',                                 languagelocalekey='en_US');         insert guestUserObj;          System.runAs(guestUserObj){             controllerObj.createPortalUser();            } }   Site.createPortalUser is always returning null in test context.    -- This post is also about same problem but no solution here.  -- This post suggests that use the System.runAs(guestUser) but does not specify how to create guest user.   If any body has solution for this..Please help me. Thanks in Advance!
61126
I am getting java.lang.NullPointerException while executing my test case , I am using Page Object Modle with PageFactory ,following are the code snippets  LoginPageObjec.java  public class LoginPageObjects {      @FindBy(xpath=".//*[@id='userName']")     private WebElement email;      @FindBy(xpath=".//*[@id='password']")     private WebElement password;      @FindBy(xpath=".//*[@id='loginFormSubmit']")     private WebElement loginBtn;      public void EnterUserName(String userName)     {         email.sendKeys(userName);     }      public void EnterPassword(String pass)     {         password.sendKeys(pass);     }      public void clickLogin()     {         loginBtn.click();     }   }   LoginTC.java  public class LoginTC extends BasePage{     private WebDriver driver;      @Test     public void login()     {         LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);         loginPage.EnterUserName("test.hr@domin.com.pk");         loginPage.EnterPassword("test");         loginPage.clickLogin();     } public void login1()         {             LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);             loginPage.EnterUserName("test.hr@domin.com.pk");             loginPage.EnterPassword("test");             loginPage.clickLogin();         }  }   BasePage.java  public class BasePage {     private WebDriver driver;      @BeforeMethod       public void initializeBrowser() {      driver=new FirefoxDriver();      driver.navigate().to("https://nexthrm-dev.vteamslabs.com/");      driver.manage().window().maximize();      }     @AfterMethod     public void closeBrowser()     {         driver.close();     }  }   I've extended BasePage class to utilize the (initialBrowser &amp; closeBrowser) functions in my test case but its producing nullpointer exception if I copy both of the functions (initialBrowser &amp; closeBrowser) into my LoginTC (testcase class) it works like charm but I dont want this redundant code i.e((initialBrowser &amp; closeBrowser) for all my testcases class could anyone explain why I am getting nullpointer exception
73252
Using C#, I need a class called User that has a username, password, active flag, first name, last name, full name, etc.    There should be methods to authenticate and save a user.  Do I just write a test for the methods? And do I even need to worry about testing the properties since they are .Net's getter and setters?
86123
I am having a hard time digging up some information on this as I believe it is still relatively new. If you implement SSO with Salesforce you have the ability to enable SAML. I have enabled SAML and have also enabled JIT with an automatically created class to support it.  Out of this newly generated class, there are two global methods that I am assuming are called upon SSO, but I do not know which one is called or how.   global User createUser(Id samlSsoProviderId, Id communityId, Id portalId,     String federationIdentifier, Map&lt;String, String&gt; attributes, String assertion) {     User u = new User();     handleJit(true, u, samlSsoProviderId, communityId, portalId,         federationIdentifier, attributes, assertion);     return u; }  global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId,     String federationIdentifier, Map&lt;String, String&gt; attributes, String assertion) {     User u = [SELECT Id, FirstName, ContactId FROM User WHERE Id=:userId];     handleJit(false, u, samlSsoProviderId, communityId, portalId,         federationIdentifier, attributes, assertion); }   Does Salesforce have some backend code that interprets the SAML coming over the SSO and then calls the methods appropriately?   The reason I am asking this is because I would like to cancel a user's SSO if they do not match x fields based off of the values coming across in the SAML in the SSO. If I did not want to update a user or create a user, would I be able to add in my own global class that could be called from the SSO?   Let me know if this is unclear / does not make sense.  Thanks
93772
below is my code Created a wrapper class like below  public class ResponseWrapper{     public list&lt;Account&gt; lstaccounts;     public boolean isError ;     public string errorCode;     public integer statusCode;        public ResponseWrapper(){          lstaccounts = new list&lt;Account&gt;();          isError= false;     }  }   and returning the wrapper class in the Httpget method  @RestResource(urlMapping='/accounts/*') global with sharing class AccountRestService { @HttpGet global static ResponseWrapper getAccounts() {     ResponseWrapper resWrap = new ResponseWrapper();     List&lt;Account&gt; accounts;      try {         accounts = [SELECT Id, Name FROM Account];         res.lstaccounts = accounts;     } catch (Exception e) {         RestResponse res = RestContext.response;         resWrap.isError = true;         res.responseBody = Blob.valueOf(e.getMessage()) = resWrap.errorCode;         res.statusCode = 500 = resWrap.statusCode;     }      return resWrap;   } }   but its throwing the Error message  Error: Compile Error: global methods do not support return type of ResponseWrapper at line 4 column 31
40567
I'm working on a project where i find i'm checking for the following in many, many places:  if(item.Rate == 0 || item.Rate == null) { }   more as a curiousity than anything, what's the best way to check for both cases?  I've added a helper method which is:  public static bool nz(object obj) {     var parsedInt = 0;     var parsed = int.TryParse(obj.ToString(), out parsedInt);     return IsNull(obj) || (parsed &amp;&amp; parsedInt == 0); }   Is there a better way?
16712
Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).  We're building a web API that's programmatically generated from a C# class. The class has method GetFooBar(int a, int b) and the API has a method GetFooBar taking query params like &amp;a=foo &amp;b=bar.   The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?
107559
I am adding cookie to my page in the controller using  ApexPages.currentPage().setCookies(new Cookie[]{CookieName});  When am trying to get the code coverage, my test class is not covering the above line.  How to get the code coverage for the above setcookie method in the test class.
117655
I have written a test class that covers 86% leaving out the apexpages.addmessage () in catch block, but majorly it throws the validation exceptions on that object when I try to update a record.(Here I am updating case status to closed and I have some custom fields to be filled out while closing the case).  My test class has 2 methods. 1st method is having the case with all the fields filled this covers all the code except catch block and 2nd method without the required fields while closing the case and even though it doesn't cover my test class to full 100%   In my case I am updating the case status to closed and while closing the case I have 2 custom fields that should not be "null" 1. xyz1__c and 2.xyz2__c (Their are validation rules written on the case object and these throwing me the exceptions if these fields are null while updating the case) I am not sure how to cover the validation exception in catch block in Test class   Can someone please provide any suggestions .  Apex controller  public with sharing class OCaseComment {     public String test2 {get;set;}     public String test1 {get;set;}     public string status {get;set;}     public casecomment ca;     public case c;     public ID caseId;     public pagereference save() {         caseId = ApexPages.currentPage().getParameters().get('caseid');         system.debug('case id entered' + caseId);         ca = new casecomment();         ca.ParentId = caseId;         ca.commentbody = 'question:' + test1 + '\n' + 'solution:' + test2;         ca.IsPublished = true;         list&lt;case&gt; c = [select Status, xyz1__c, xyz2__c from case where ID =: caseId];         list&lt;case&gt; cg = new list&lt;case&gt;();         for (case cd : c) {             cd.Status = 'Closed';             cg.add(cd);         }         try {             if (cg.size() &gt; 0 &amp;&amp; cg[0].xyz1__c != null &amp;&amp; cg[0].xyz2__c != null) {                 insert ca;             }             update cg;             status = 'saved';             system.debug('status value' + status);         } catch (DmlException d) {             Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage()));             status = 'unsaved';         }         return null;     } }   Test class   @isTest public class TestClassOCaseComment {     @isTest public static void withcaseid() {         case c = new         case (status = 'New', Origin = 'Phone', xyz1__c = 'Stats', xyz2__c = 'Issues');         insert c;         case ca = [select id, status, xyz2__c from             case where status = 'New'         ];         Test.setCurrentPage(page.SCaseComments);         OCaseComment cs = new OCaseComment();         cs.Test1 = ('test1');         cs.Test2 = ('test2');         apexpages.currentPage().getparameters().put('caseid', ca.id);         if (ca.id != null) {             cs.save();         }         casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];         string str = 'Question:' + cs.test1 + '\n' + 'Solution:' + cs.test2;         system.assertEquals(str, cm.CommentBody);         system.assert(true, cm.ispublished);         case g = [select Status from             case where ID = :                 ca.Id         ];         system.assertEquals('Closed', g.status);     }     @isTest static void caseWithoutproduct() {         try {             case c = new             case (status = 'New', Origin = 'Phone', xyz2__c = 'Issues');             insert c;             pagereference pr = page.SCaseComments;             pr.getParameters().put('caseid', c.Id);             test.setCurrentPage(pr);             OCaseComment cc = new OCaseComment();             cc.save();         } catch (Exception e) {             System.Assert(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'));             System.Assert(e.getMessage().contains('xyz1__c'));         }     } }
7236
I have a scenario, in case of the user registration successful, it will display a success message on the next page otherwise an error message shows on the same page. How to automate the test case to return as passed if it is success and failure in case of error message comes up.  Please help me out here.
99589
I am stuck on the prevent SOQL injection trailhead, where I am looking to determine which portions of the code I would need to invoke escapeSingleQuotes or whitelist to enable. I've made several attempts at investigation to little avail. I have appended my code are there any steps I would need to take. My goal is to assess the code to see how it works and what I would need to do.  public class Prevent_SOQL_Injection_Challenge {  public string textOne {get; set;} public string textTwo {get; set;} public string comparator {get; set;} public string numberOne {get; set;}  public List&lt;Supply__c&gt; whereclause_records {get; set;}   public PageReference stringSearchOne(){     string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';     string whereClause = '';      if(textOne != null &amp;&amp; textOne!=''){             whereClause += 'name like  \'%'+string.escapeSingleQuotes(textOne)+'%\' ';     }      if(whereClause != ''){         whereclause_records = database.query(query+' where '+whereClause+' Limit 10');     }      return null; }   public PageReference stringSearchTwo(){     string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';     string whereClause = '';      if(textTwo != null &amp;&amp; textTwo!=''){             whereClause += 'Storage_Location__r.name like  \'%'+string.escapeSingleQuotes(textTwo)+'%\' ';     }      if(whereClause != ''){         whereclause_records = database.query(query+' where '+whereClause+' Limit 10');     }      return null; }   public PageReference numberSearchOne(){     string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';     string whereClause = '';      if(numberOne != null &amp;&amp; comparator != null){         whereClause += 'Quantity__c '+comparator+' '+string.ValueOf(numberOne)+' ';     }      if(whereClause != ''){         whereclause_records = database.query(query+' where '+string.ValueOf(whereClause)+' Limit 10');     }      return null; } }
18034
when i try to save the following code, i got the error below. Following same instructions given in this link, but still errors. Am i doing anything wrong here? please suggest.    @isTest private class WebSvcCalloutTest {     @isTest static void testEchoString() {         Account a = new Account(name='Tester',SAP_KUNNR__c='1172');         insert a;                       // This causes a fake response to be generated         Test.setMock(WebServiceMock.class, new WebServiceMockImpl());      } }   Error:  Save error: Method does not exist or incorrect signature: Test.setMock(Type, WebServiceMockImpl)    WebSvcCalloutTest.cls         @isTest global class WebServiceMockImpl implements WebServiceMock {    global void doInvoke(            Object stub,            Object request,            Map&lt;String, Object&gt; response,            String endpoint,            String soapAction,            String requestName,            String responseNS,            String responseName,            String responseType) {          sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00 sap1 = new sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00();                Map&lt;String,String&gt; mapSAP = new Map&lt;String,String&gt; {};         sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01 req = new sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01();               sapComDocumentSapSoapFunctionsMcS.ZGssmwfmHndlEvntrqst00Response_element ret =  sap1.ZGssmwfmHndlEvntrqst00('',req);         response.put('response_x', ret);     } }
106099
I'm working on developing a test class for my apex. I'm stuck with creation of Contract records contractnumber field. In test class, I use the following code:     Contract c = new Contract();     c.Name = 'Test Contract';     c.AccountId = acc.Id;     c.Status = 'Draft';     insert c;     //I'm creating a draft contract and then activating it.     c.status  = 'Activated';     update c;     system.debug('contract debug:'+c.contractnumber);  Contractnumber field on object is Autonumber, but in the log I get null for contractnumber. I see the whole contract record is created with null ContractNumber. What am I doing wrong?
115896
I need some basic Unit Test writing assistance.   My method just runs a SOQL query to filter a contact list for service cloud. What's the best way to test it?  Here is the class:   public class ContactsListController{     public ContactsListController(ApexPages.StandardController stdController) {         this.acct = (Account)stdController.getRecord();     }      private final Account acct;       public List&lt;Contact&gt; getContacts() {         List&lt;Account&gt; acct =              [SELECT id              FROM Account              WHERE id = :ApexPages.currentPage().getParameters().get('id')];          List&lt;Contact&gt; results =             [SELECT Id, AccountId, Full_Name__c, Email, Phone, Title              FROM Contact               WHERE (AccountId = :acct AND No_Longer_with_Company__c = False)];          return results;     } }   The unit test inserts 50 new contacts, should I call to my getContacts method to get code coverage? Any pointers would be greatly appreciated.   Unit Test:   @isTest class ContactsListControllerTest {     static testMethod void testContactList (){         //Insert 50 test contacts         List&lt;Contact&gt; contacts = new List&lt;Contact&gt;();          for (Integer count = 0; count &lt; 50; count++) {             contacts.add(new Contact (FirstName = 'John'+count, LastName ='Doe'+count));         }          insert contacts;      }   }
39303
I have a working login form in an asp.net application.  Standard stuff with a username and password text box and a button to process the login.  Works fine.  I have a new requirement to allow the user to input the username and password from a separate plain html page that is not a part of my asp.net application.  I plan on achieving this using standard html - form, input, submit button etc.  The form action will be the URL of my asp.net login page and its method will be POST.    What I want to do in the C# code behind page of the asp.net login form, presumably in the Page_Load event, is to check if the request for the page contains a username and password value being passed in.  If it does then I need to read those values and process the login as if someone had clicked the login button on the asp.net page.  If not then I will display the login form as usual.    How do I check for the existence of, and read, the username and password values in the request for my page.
82873
I am trying to learn how to do APEX testing but all the tests in the documentation are too complex and I can't find an example of a simple APEX Controller that is a Hello World Test.  I have this APEX Code  public class MessageMaker{ public static string helloMessage() {     return('You say "Goodbye," I say "Hello"');     } }   Should I be testing that the String is the same? Here is my test that doesn't work      @isTest public class MessageMakerTest {     public static testMethod void testMyClass(){         MessageMaker controller = new MessageMaker();         String helloMessage = helloMessage();          System.assertEquals(helloMessage, 'You say "Goodbye," I say "Hello"');      } }   I am getting this error.       Method does not exist or incorrect signature: helloMessage()   I have some more advanced APEX code but I want to understand what I need to test for and how before I can do that.  Thank you in advance.
110676
How can I use the CreateUser method in the Membership class without having to assign a question and answer?  I have disabled it in the web.config with the following setting.  requiresQuestionAndAnswer="false"   I need the status output from the CreateUser method, but the overload requires a question and answer. Can anyone suggest how I can go about this?