• Yelper Dev
  • NEWBIE
  • 35 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 8
    Replies
Do you have any idea on how we can include the code below in test class especially on messageErrorResp(); ?

Thank you.
 
public class headResponse {
        public String code { get; set; }
        public Integer httpStatus { get; set; }
        public String message { get; set; }
        public String moreInfo { get; set; }
        public String severity { get; set; }
        public String transId{ get; set; }
        
        public headResponse(){
            code = null;
            httpStatus = null;
            message = null;
            moreInfo = null;
            severity = null;
            transId = null;
        }
    }
 
 @TestVisible private void messageErrorResp(HttpResponse response){
        headResponse errorResponse;
        try{
            errorResponse = (headResponse)JSON.deserialize(response.getBody(),headResponse.class);
        } 
        catch(Exception e){
            // Could not parse the JSON response so likely a HTTP error (eg. timeout)
            throw new Exception('Call to backend services returned a ' + response.getStatusCode() + ' ' + response.getStatus());
        }   
        throw new Exception('Call to backend services returned ' + errorResponse.code + ' - ' + errorResponse.message);
    }

 
Hi badly need help, error says "System.NullPointerException: Attempt to de-reference a null object" for the following test class below.
 
@isTest static void getViewDataWithoutPermission() {
        getAllRecords();
        Test.startTest();
        User u = setUser(false);
        System.runAs(u) {
            List<Authorisation__c> auths = AuthorisedAccessForController.getViewData(acc2.Id);
            Integer count = 0;
            for (Authorisation__c autho : auths) {
                List<ProductAuthorisation__c> pas = autho.Product_Authorisations__r;
                if (pas != null && !pas.isEmpty()) {
                    count =+ pas.size();
                }
                system.debug('@@@TEST::count'+count);
            }
            Test.stopTest();
            system.debug('@@@TEST::AUTH'+auths);
            //System.assertEquals(1, auths.size());
            //System.assertEquals(1, count);
        }
    }
I modularized the User by creating a boolean class "setUser"
 
static User setUser(Boolean withPS) {
        Profile p = [Select Id from Profile where NAME = 'System Administrator'];
        
        User u = new User(
            ProfileId = p.Id,
            Username = 'testclass123@racv.com',
            Alias = 'tclass',
            Email='testclass123@racv.com',
            EmailEncodingKey='UTF-8',
            Firstname='Spongebob',
            Lastname='Squarepants',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
			insert u;
	      
        
        if (withPS) {
            PermissionSet ps = [SELECT ID From PermissionSet WHERE Name = 'AuthorisationAccess'];
			insert new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = ps.Id );
        }
           return u;
       
    }
Question, why is it returning null value?

This is my controller:
public static List<Authorisation__c> getViewData(String customerId) {
        List<Authorisation__c> dataList = new List<Authorisation__c>();
        
        try {
            dataList = Database.query(getQuery(customerId));
            
            
            if ((dataList == NULL || dataList.isEmpty()) && Test.isRunningTest()) {
                System.debug('Throwing exception');
                throw new mexException();
            }
        } catch (Exception e) {
            UTIL_LoggingService.logHandledException(e, ORG_ID, APP_NAME, CLASS_NAME, 'getViewData', null, LOGGING_LEVEL);
        }
        
        if(dataList.size() > 0) {
            return dataList;
        } else {
            return null;
        }
    }


 
Hello, Can anyone help me with the following requirements? The even of the trigger is before Insert.

[1] If there is no contact records on the Account, the new contact record should be automatically be the primary contact (Checkbox field)

[2] If 2 Account has no contact records, the 2 new contact records should be automatically be the primary contact.

[3] If the Account has already a contact record that is already a Primary, it should prompt an error message "Already has primary contact"

Contact Trigger:
trigger ContactTrigger on Contact (before insert, before update) {
    if(Trigger.isBefore){
        if(Trigger.isInsert){
             ContactTriggerHandler.doBeforeInsert(Trigger.new);
        }
         if(Trigger.isUpdate){
         ContactTriggerHandler.onBeforeUpdate(Trigger.new, Trigger.oldMap);
        }
    }
}
Thank you.
Hello, can you please help me on how to write a test class method for the ff. snippet below. I used schema to have my picklsit be dynamic in visual force page.
 
public List<SelectOption> getAccountTypeOptionsList(){
        List<SelectOption> accountTypeOptionsList = new List<SelectOption>{new SelectOption('', '--None--')};
            Schema.DescribeFieldResult accountTypeDescription = Account.Type.getDescribe();
        List<Schema.PicklistEntry> accountTypePicklistValuesList = accountTypeDescription.getPicklistValues();
        for(Schema.PicklistEntry accountTypePicklistValue : accountTypePicklistValuesList){
            accountTypeOptionsList.add(new SelectOption(accountTypePicklistValue.getLabel(), accountTypePicklistValue.getValue()));
        }
        return accountTypeOptionsList;
    }

I need also the assertion. Thank you.
 
Hi, I need help with code. The requirement is to display all the records of Contact that has Account. When I search, there is no results being displayed. Anything wrong with my custom controller? Just a reminder I've created a Wrapper Class for this dynamic Search.

Custom Controller:
public with sharing class AccountSearchSampleController{
    //Pagination variables
    public Integer pageCount = 0;
    public Integer currentPage = 1;
    public Integer pageLimit = 10;
    public Integer totalSize = 0;
    
    public String resultDateTime{get;set;}
    
    //Search Criteria fields variables
    public String AccountName {get;set;}	
    public String Country {get;set;}
    public String ContactName {get;set;}
    public String AccountType {get;set;}
    
    //Custom Setting variable class
    public Account_Filter__c searchSetting {get;set;}
    
    //Wrapper class
    public Map<Integer, List<ContactWithAccountWrapper>> accountSearchResultMap;

    //Constructor
    public AccountSearchSampleController(){
        //Initialize accountSearchResultMap to empty map
        this.accountSearchResultMap = new Map<Integer, List<ContactWithAccountWrapper>>();

        //Returns the custom setting data set record for the specified data set name.
        searchSetting = Account_Filter__c.getInstance();
        pageLimit = Integer.valueOf(searchSetting.Page_Limit__c);
    }     
    //For dynamic picklist of Account Type field
    public List<SelectOption> getAccountTypeOptionsList(){
        List<SelectOption> accountTypeOptionsList = new List<SelectOption>{new SelectOption('', '--None--')};
            Schema.DescribeFieldResult accountTypeDescription = Account.Type.getDescribe();
        List<Schema.PicklistEntry> accountTypePicklistValuesList = accountTypeDescription.getPicklistValues();
        for(Schema.PicklistEntry accountTypePicklistValue : accountTypePicklistValuesList){
            accountTypeOptionsList.add(new SelectOption(accountTypePicklistValue.getLabel(), accountTypePicklistValue.getValue()));
        }
        return accountTypeOptionsList;
    }

    //Displays error message method
    public Boolean checkFilterValidation(){
        Boolean valid = FALSE;
        
        if(this.Country	 != NULL){
            this.Country = this.Country.replace('*', '');
        }
        if(this.ContactName	 != NULL){
            this.ContactName = this.ContactName.replace('*', ''); 
        }
        Set<String> filterSet = new Set<String>{this.AccountName, this.Country, this.ContactName, this.AccountType};
            for(String filter : filterSet){
                if(!String.isBlank(filter)){
                    valid = TRUE;
                }
            }
        
        //Displays an error message if all fields does not have a value to search.
        if(!valid){
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.Severity.ERROR, Label.LBL_Account_Search_No_Value);
            ApexPages.addMessage(errorMessage);
            return valid;
        }
        //Displays an error message if Account Name field does not have a value and should at least be 2 minimum characters to search.
        if(!String.isBlank(AccountName) && AccountName.length() < 2){
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.Severity.ERROR, Label.LBL_Account_Search_Minimum_Character_Input);
            ApexPages.addMessage(errorMessage);
            valid = FALSE;
        }
        return valid;
    }


    //Start of Logic query - Trigger to search based on the criteria
    public void searchAccounts(){
        if(checkFilterValidation()){
            this.currentPage = 1;
            //Initialize accountSearchResultMap
            fetchRecords();
        } 
    } 
    
    //To pull the records if "Find Account" button is click
    public void fetchRecords(){
        this.accountSearchResultMap = new Map<Integer, List<ContactWithAccountWrapper>>();
        Set<Id> accountIdSet = new Set<Id>();
        Map<Id, Account> accountMap = new Map<Id, Account>();
        List<Account> accountContactList = new List<Account>();
        
        //Pass the method to string variable
        String queryString = getQueryString();
        
        //The string variable will retrieve up to 50,000 records.
        accountContactList = Database.query(queryString);
        this.resultDateTime = System.now().format('MMM, DD YYY \'@\' HH:mm:ss z');
        remapForPagination(accountContactList);
    }
    
    //Query Conditions
    public String getQueryString(){
        String tempCondition = '';
        String contactCondition = '';
        List<String> conditionList = new List<String>{'isDeleted = FALSE'};
            //Parent to Child Query - To validate if the record has been deleted or not.
            String contactSubQuery = 'SELECT Id, Name, CreatedDate 	FROM Contacts WHERE isDeleted = FALSE';
        
        //Start of Query for Account Name field
        if(!String.isBlank(this.AccountName)){
            //Returns a copy of the string that no longer contains any leading or trailing white space characters.
            this.AccountName = this.AccountName.trim();
            tempCondition = stringConditionHandler(this.AccountName, TRUE);
            conditionList.add('Name LIKE \'' + tempCondition + '\'');
            
        }  
        //Start of Query for Country field
        if(!String.isBlank(this.Country)){
            //Returns a copy of the string that no longer contains any leading or trailing white space characters.
            this.Country = this.Country.replace('*', '').trim();
            tempCondition = stringConditionHandler(this.Country, FALSE);
            conditionList.add('(BillingCountry = \'' + tempCondition + '\' + OR ShippingCountry = \'' + tempCondition + '\')');
        }    
        
        //Start of Query for Contact Name field
        if(!String.isBlank(this.ContactName)){
            //Returns a copy of the string that no longer contains any leading or trailing white space characters.
            this.ContactName = this.ContactName.replace('*', '').trim();
            tempCondition = stringConditionHandler(this.ContactName, FALSE);
            contactCondition = 'AND (Name = \'' + tempCondition + '\' + OR FirstName = \'' + tempCondition + '\' OR LastName = \'' + tempCondition + '\')';
            conditionList.add('Id IN (SELECT AccountId FROM Contact WHERE ' + contactCondition + ')');
            contactSubQuery += contactCondition;
        }
        
        //Start of Query for Account Type
        if(!String.isBlank(this.AccountType)){
            tempCondition = stringConditionHandler(this.AccountType, FALSE);
            conditionList.add('(Type = \'' + tempCondition + '\' ');
        }  
        
        String queryString = 'SELECT Id, Name, CreatedDate, BillingCountry, ShippingCountry, Type, ( ' + contactSubQuery + ' ) FROM Account WHERE Name LIKE \'%'+AccountName+'%\' ORDER BY Name';
        System.debug(queryString);
        return queryString;
    }
    
    //For replacing wildcard character 
    public String stringConditionHandler(String value, Boolean withWildCard){
        String processedValue = value;
        if(withWildCard){
            processedValue = value.replace('%', '\\%').replace('_', '\\').replace('*', '%');
        }else{
            processedValue = value.replace('*', '');
        }
        return String.escapeSingleQuotes(processedValue).trim();
    }
    
    //For pagination using Map
    public void remapForPagination(List<Account> accountContactList){
        Integer recordsPerPageCounter = 0;
        Integer pageCounter = 1;
        Integer totalRecords = 0;
        
        for(Account acct : accountContactList){
            if(acct.Contacts.size() > 0){
                for(Contact cont : acct.Contacts){
                    totalRecords++;
                    System.debug(totalRecords);
                    if(recordsPerPageCounter < this.PageLimit){
                        recordsPerPageCounter++;
                        System.debug(recordsPerPageCounter);
                    }else{
                        recordsPerPageCounter = 1;
                        pageCounter++;
                        System.debug(recordsPerPageCounter + pageCounter);
                    }
                    
                    if(this.accountSearchResultMap.containsKey(pageCounter)){
                        this.accountSearchResultMap.put(pageCounter, new List<ContactWithAccountWrapper>());
                        System.debug(accountSearchResultMap);
                    }
                    this.accountSearchResultMap.get(pageCounter).add(new ContactWithAccountWrapper(cont, acct));
                }
            }else{
                totalRecords++;
                if(recordsPerPageCounter < this.pageLimit){
                    recordsPerPageCounter++;
                } else{
                    recordsPerPageCounter = 1;
                    pageCounter++;
                }
                if(!this.accountSearchResultMap.containsKey(pageCounter)){
                    this.accountSearchResultMap.put(pageCounter, new List<ContactWithAccountWrapper>());
                }
                this.accountSearchResultMap.get(pageCounter).add(new ContactWithAccountWrapper(new Contact(), acct));
            }
        }
        this.totalSize = totalRecords;
    }
    
    //Wrapper to assign and get the results to be displayed in visualforce page
    public List<ContactWithAccountWrapper> getSearchResultList(){
        return this.accountSearchResultMap.get(currentPage);
    }

    //Pagination
        public Integer getTotalSize(){
        return this.totalSize;
    }
    
    public Boolean getFirst(){
        return
    }
    public Boolean getHasNext(){
        return this.accountSearchResultMap.containsKey(currentPage + 1);
    }
   
    public void getNext(){
        this.currentPage++;
    }

    public void getLast(){
        return this.accountSearchResultMap.size();
    }
    
    public Boolean getHasPrevious(){
        return this.accountSearchResultMap.containsKey(currentPage - 1);
    }
    
    public void getPrevious(){
        this.currentPage--;
    }

    public void getFirst(){
    this.currentPage =1;
    }
    
    //Wrapper class for Account and Contact Object
    public class ContactWithAccountWrapper{
        public Account acct {get; set;}
        public Contact cont {get; set;}
        public Integer yearAccountCreated {get; set;}
        public ContactWithAccountWrapper(Contact contact, Account account){
            this.cont = contact;
            this.acct = account;
            yearAccountCreated = account.CreatedDate.year();
        }
    }
    
}
Visualforce page:
<apex:page controller="AccountSearchSampleController" tabStyle="Account_Search_Sample__tab">
    <!--Custom CSS File for Account Search Page-->
    <apex:stylesheet value="{! $Resource.AccountSearchPageCSS}"/>
    <!--Start of Searching For Matching Records-->
    <apex:actionstatus id="matching_records">
        <apex:facet name="start">
            <apex:outputPanel styleClass="waitingSearchDiv">
                <apex:outputPanel styleClass="waitingHolder">
                    <apex:image url="/img/loading.gif" />
                    <apex:outputPanel >{! $Label.LBL_Search_Matching_Accounts}</apex:outputPanel>
                </apex:outputPanel>
            </apex:outputPanel>
        </apex:facet>
    </apex:actionstatus>
    <!--End of Searching For Matching Records --> 
    <!--Start of Loading Records-->
    <apex:actionstatus id="loading_records">
        <apex:facet name="start">
            <apex:outputPanel styleClass="waitingSearchDiv">
                <apex:outputPanel styleClass="waitingHolder">
                    <apex:image url="/img/loading.gif" />
                    <apex:outputPanel >{! $Label.LBL_Loading_Records}</apex:outputPanel>
                </apex:outputPanel>
            </apex:outputPanel>
        </apex:facet>
    </apex:actionstatus>
    <!--End of Loading Records-->        
    <apex:form >
        <!--Logo of Account Search Page-->
        <apex:image url="{! $Resource.AccountSearchLogo}"/> 
        <!--Error Message-->
        <apex:pageMessages id="showErrorMessage" />
        <apex:pageBlock title="{! $Label.LBL_Search_Criteria}" helpUrl="{! $Label.LBL_How_to_Search}" helpTitle="{! $Label.LBL_How_to_Search}">
            <apex:pageBlockSection columns="4">
                <apex:pageBlockSection columns="1">
                    <apex:outputText value="{!$ObjectType.Account.Fields.Name.Label}" styleclass="labelBold"/>
                    <apex:inputText value="{! AccountName}" required="FALSE"/>
                </apex:pageBlockSection>
                <apex:pageBlockSection columns="1" rendered="{! searchSetting.Country__c }">
                    <apex:outputText value="{!$Label.LBL_Country}" styleclass="labelBold"/>
                    <apex:inputText value="{! Country}"/>
                </apex:pageBlockSection>
                <apex:pageBlockSection columns="1"  rendered="{! searchSetting.Contact_Name__c }">
                    <apex:outputText value="{!$Label.LBL_Contact_Name}" styleclass="labelBold"/>
                    <apex:inputText value="{! ContactName}" rendered="{! searchSetting.Contact_Name__c }"/>    
                </apex:pageBlockSection>
                <apex:pageBlockSection columns="1" rendered="{! searchSetting.Account_Type__c}">
                    <apex:outputText value="{!$ObjectType.Account.Fields.Type.Label}" styleclass="labelBold" />
                    <apex:selectList value="{! AccountType}" rendered="{! searchSetting.Account_Type__c}" size="1">
                        <apex:selectOptions value="{! accountTypeOptionsList}"/>
                    </apex:selectList> 
                </apex:pageBlockSection>  
            </apex:pageBlockSection>  
            <apex:pageBlockButtons location="bottom" styleClass="findAcctButton">
                    <apex:commandButton value="Find Acccounts" status="matching_records" rerender="showErrorMessage"  action="{! searchAccounts}" /> 
            </apex:pageBlockButtons>
        </apex:pageBlock>
        <!--Start of Search Results Block--> 
        
        <apex:pageBlock title="{! $Label.LBL_Search_Results}" id="search-result">
            <!--Start of Displaying Results-->
            <apex:outputText rendered="{! !(SearchResultList.empty || SearchResultList == NULL) }" value="{ ! SearchResultList.size}/{! totalSize} {! $Label.LBL_Search_Results}" /> 
            <!--Enod of Displaying Results-->
            <apex:outputPanel layout="block" >
                <apex:pageBlockTable value="{! searchResultList}" var="searchResult" rendered="{! !(SearchResultList.empty || SearchResultList == NULL) } ">
                    <apex:column headerValue="{!$ObjectType.Account.Fields.Name.Label}"/>
                    <apex:outputLink value="/{! searchResult.acct.Id}" target="_blank">
                        {! searchResult.acct.Name}
                    </apex:outputLink>
                    <apex:column value="{! searchResult.acct.BillingCountry}" headerValue="{!$ObjectType.Account.Fields.BillingCountry.Label}"/>  
                    <apex:column value="{! searchResult.acct.ShippingCountry}" headerValue="{!$ObjectType.Account.Fields.ShippingCountry.Label}"/>  
                    <apex:column headerValue="{!$Label.LBL_Contact_Name}"/>
                    <apex:outputLink value="/{! searchResult.cont.Id}" target="_blank">
                        {! searchResult.cont.Name}
                    </apex:outputLink>
                    <apex:column value="{! searchResult.acct.Type}" headerValue="{!$ObjectType.Account.Fields.Type.Label}"/>  
                    <apex:column value="{! searchResult.yearAccountCreated}" headerValue="{! $Label.LBL_Year_Created}"/>
                </apex:pageBlockTable>
                <apex:outputPanel layout="block" rendered="{! SearchResultList.empty || SearchResultList == NULL }">
                {! $Label.LBL_Matching_Records}
                </apex:outputPanel>
            </apex:outputPanel>
                        <apex:outputPanel >
                <apex:commandButton value="{! $Label.LBL_Double_Previous_Button}" action="{! getFirst}" rendered="{! hasPrevious}" rerender="search-result" status="loading_records" disabled="{!prev}"/>
                <apex:commandButton value="{! $Label.LBL_Previous_Button}" action="{! getFirst}" rendered="{! hasPrevious}" rerender="search-result" status="loading_records" disabled="{!prev}"/>
                <apex:commandButton value="{! $Label.LBL_Next_Button}" action="{! getNext}" rendered="{! hasNext}" rerender="search-result" status="loading_records" disabled="{!next}"/>
                <apex:commandButton value="{! $Label.LBL_Double_Next_Button}" action="{! getLast}" rendered="{! hasNext}" rerender="search-result" status="loading_records" disabled="{!next}"/>
            </apex:outputPanel>
        </apex:pageBlock>
        <!--End of Search Results Block--> 
    </apex:form>
</apex:page>


 
Hello,

Need some help in creating test class for the following extension bellow. I am using an Account standardcontroller.
 
public class GetContactFromAccount {
    
    public Contact contact {get;set;}
    public Account account {get;set;}
    private final ApexPages.StandardController controller;
    
    public getContactFromAccount(ApexPages.StandardController controller){
        this.controller = controller;
        account = (Account)controller.getRecord();
        contact = new Contact();
    }    
    
    public PageReference save(){
        insert account;
        contact.MailingStreet = account.BillingStreet;
        contact.MailingCity = account.BillingCity;
        contact.MailingState = account.BillingState;
        contact.MailingPostalCode = account.BillingPostalCode;
        contact.MailingState = account.BillingCountry;        
        contact.AccountId = account.Id;
        contact.Type__c = 'Subscriber';
        insert contact;
        Pagereference pageRef = New PageReference('/'+account.Id);
        System.debug(contact);
        return pageRef;
    }
    
}

Thank you!
Hi  need help on creating test class for the code below: 
public static void copyContactMailingAddress(List<Account> acctList, Map<Id, Account> oldAcctMap){
        //Returns all new keys contain in the oldAcctMap
        Set<Id> acctNewId = Trigger.newMap.keyset();
        for (Account acct : acctList){
            Account oldAcctRecord = oldAcctMap.get(acct.Id);
            //Query all contactRecords with their mailing address
            List<Contact> contactRecord = [SELECT id, accountId, MailingStreet, MailingCity, MailingCountry, MailingPostalCode, MailingState
                                           FROM Contact
                                           WHERE accountId in : acctNewId]; 
            
            //Compare values from old to new billing address.
            for (Contact con : contactRecord) {   
                if (oldAcctRecord.BillingStreet != acct.BillingStreet
                   || oldAcctRecord.BillingCity != acct.BillingCity
                   || oldAcctRecord.BillingState != acct.BillingState
                   || oldAcctRecord.BillingPostalCode != acct.BillingPostalCode
                   || oldacctRecord.BillingCountry != acct.BillingCountry){
                    con.MailingStreet = acct.BillingStreet;
                    con.MailingCity = acct.BillingCity;
                    con.MailingState = acct.BillingState;
                    con.MailingPostalCode = acct.BillingPostalCode;
                    con.MailingState = acct.BillingCountry;
                }
           }
            //DML Statement to update the Billing Address that is in the Account to all related contacts
            update  contactRecord;
        }       
    }

The trigger is in before update, already have test factory for this:
@isTest
public TestDataFactory{
public static List<Account> createAcctWithCon(Integer numAcct, Integer numConPerAcct){
        List<Account> acct = new List<Account>();
        
        for(Integer i = 0; i < numAcct; i++){
            Account a = new Account(Name = 'Test Account' + i);
            acct.add(a);
        }
        insert acct; 
        
        List<Contact> con = new List<Contact>();
        for(Account at : acct){
            for(Integer j = 0; j < numAcct; j++){
                con.add(new Contact (LastName = at.Name + 'Contact' + j, AccountId = at.Id));
            }
        }
        insert con;
        return acct;
    }
}

Much need help thank you!
Hello,

Would like to ask on how to create a testdatafactory and test class for the following code below?

Trigger Handler:
public class OpportunityTriggerHandler {
    public static void onBeforeUpdate(List<Opportunity> oppList, Map<Id, Opportunity> oldStageMap){
        oppNewStage(oppList, oldStageMap);
    }
	
    public static void oppNewStage(List<Opportunity> oppList, Map<Id, Opportunity> oldStageMap){
        for(Opportunity opp : oppList){
            //Compare the old stage status and new stage status.
            Opportunity oldOppID = oldStageMap.get(opp.Id);           
                if(oldOppID.StageName !=opp.StageName){
                    if(opp.StageName == 'Closed Won'){
                        opp.Description = 'This Opportunity is Closed Won.';
                    }                    
                }           
        }
    }
}
And Trigger is:
trigger OpportunityTrigger on Opportunity (before update) {
    if(Trigger.isBefore)
    {        
        if(Trigger.isUpdate){
            OpportunityTriggerHandler.onBeforeUpdate(Trigger.new, Trigger.oldMap);
        }
    }
}

Thank you!
 
Hi there, how do you pull/retrieve the Org's Account, Contact, Lead, etc, Classes & Objects, into VS Code? I can see only Custom Objects. Thanks!!
Hi badly need help, error says "System.NullPointerException: Attempt to de-reference a null object" for the following test class below.
 
@isTest static void getViewDataWithoutPermission() {
        getAllRecords();
        Test.startTest();
        User u = setUser(false);
        System.runAs(u) {
            List<Authorisation__c> auths = AuthorisedAccessForController.getViewData(acc2.Id);
            Integer count = 0;
            for (Authorisation__c autho : auths) {
                List<ProductAuthorisation__c> pas = autho.Product_Authorisations__r;
                if (pas != null && !pas.isEmpty()) {
                    count =+ pas.size();
                }
                system.debug('@@@TEST::count'+count);
            }
            Test.stopTest();
            system.debug('@@@TEST::AUTH'+auths);
            //System.assertEquals(1, auths.size());
            //System.assertEquals(1, count);
        }
    }
I modularized the User by creating a boolean class "setUser"
 
static User setUser(Boolean withPS) {
        Profile p = [Select Id from Profile where NAME = 'System Administrator'];
        
        User u = new User(
            ProfileId = p.Id,
            Username = 'testclass123@racv.com',
            Alias = 'tclass',
            Email='testclass123@racv.com',
            EmailEncodingKey='UTF-8',
            Firstname='Spongebob',
            Lastname='Squarepants',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
			insert u;
	      
        
        if (withPS) {
            PermissionSet ps = [SELECT ID From PermissionSet WHERE Name = 'AuthorisationAccess'];
			insert new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = ps.Id );
        }
           return u;
       
    }
Question, why is it returning null value?

This is my controller:
public static List<Authorisation__c> getViewData(String customerId) {
        List<Authorisation__c> dataList = new List<Authorisation__c>();
        
        try {
            dataList = Database.query(getQuery(customerId));
            
            
            if ((dataList == NULL || dataList.isEmpty()) && Test.isRunningTest()) {
                System.debug('Throwing exception');
                throw new mexException();
            }
        } catch (Exception e) {
            UTIL_LoggingService.logHandledException(e, ORG_ID, APP_NAME, CLASS_NAME, 'getViewData', null, LOGGING_LEVEL);
        }
        
        if(dataList.size() > 0) {
            return dataList;
        } else {
            return null;
        }
    }


 
Hello, can you please help me on how to write a test class method for the ff. snippet below. I used schema to have my picklsit be dynamic in visual force page.
 
public List<SelectOption> getAccountTypeOptionsList(){
        List<SelectOption> accountTypeOptionsList = new List<SelectOption>{new SelectOption('', '--None--')};
            Schema.DescribeFieldResult accountTypeDescription = Account.Type.getDescribe();
        List<Schema.PicklistEntry> accountTypePicklistValuesList = accountTypeDescription.getPicklistValues();
        for(Schema.PicklistEntry accountTypePicklistValue : accountTypePicklistValuesList){
            accountTypeOptionsList.add(new SelectOption(accountTypePicklistValue.getLabel(), accountTypePicklistValue.getValue()));
        }
        return accountTypeOptionsList;
    }

I need also the assertion. Thank you.
 
Hello,

Need some help in creating test class for the following extension bellow. I am using an Account standardcontroller.
 
public class GetContactFromAccount {
    
    public Contact contact {get;set;}
    public Account account {get;set;}
    private final ApexPages.StandardController controller;
    
    public getContactFromAccount(ApexPages.StandardController controller){
        this.controller = controller;
        account = (Account)controller.getRecord();
        contact = new Contact();
    }    
    
    public PageReference save(){
        insert account;
        contact.MailingStreet = account.BillingStreet;
        contact.MailingCity = account.BillingCity;
        contact.MailingState = account.BillingState;
        contact.MailingPostalCode = account.BillingPostalCode;
        contact.MailingState = account.BillingCountry;        
        contact.AccountId = account.Id;
        contact.Type__c = 'Subscriber';
        insert contact;
        Pagereference pageRef = New PageReference('/'+account.Id);
        System.debug(contact);
        return pageRef;
    }
    
}

Thank you!
Hi  need help on creating test class for the code below: 
public static void copyContactMailingAddress(List<Account> acctList, Map<Id, Account> oldAcctMap){
        //Returns all new keys contain in the oldAcctMap
        Set<Id> acctNewId = Trigger.newMap.keyset();
        for (Account acct : acctList){
            Account oldAcctRecord = oldAcctMap.get(acct.Id);
            //Query all contactRecords with their mailing address
            List<Contact> contactRecord = [SELECT id, accountId, MailingStreet, MailingCity, MailingCountry, MailingPostalCode, MailingState
                                           FROM Contact
                                           WHERE accountId in : acctNewId]; 
            
            //Compare values from old to new billing address.
            for (Contact con : contactRecord) {   
                if (oldAcctRecord.BillingStreet != acct.BillingStreet
                   || oldAcctRecord.BillingCity != acct.BillingCity
                   || oldAcctRecord.BillingState != acct.BillingState
                   || oldAcctRecord.BillingPostalCode != acct.BillingPostalCode
                   || oldacctRecord.BillingCountry != acct.BillingCountry){
                    con.MailingStreet = acct.BillingStreet;
                    con.MailingCity = acct.BillingCity;
                    con.MailingState = acct.BillingState;
                    con.MailingPostalCode = acct.BillingPostalCode;
                    con.MailingState = acct.BillingCountry;
                }
           }
            //DML Statement to update the Billing Address that is in the Account to all related contacts
            update  contactRecord;
        }       
    }

The trigger is in before update, already have test factory for this:
@isTest
public TestDataFactory{
public static List<Account> createAcctWithCon(Integer numAcct, Integer numConPerAcct){
        List<Account> acct = new List<Account>();
        
        for(Integer i = 0; i < numAcct; i++){
            Account a = new Account(Name = 'Test Account' + i);
            acct.add(a);
        }
        insert acct; 
        
        List<Contact> con = new List<Contact>();
        for(Account at : acct){
            for(Integer j = 0; j < numAcct; j++){
                con.add(new Contact (LastName = at.Name + 'Contact' + j, AccountId = at.Id));
            }
        }
        insert con;
        return acct;
    }
}

Much need help thank you!
Hello,

Would like to ask on how to create a testdatafactory and test class for the following code below?

Trigger Handler:
public class OpportunityTriggerHandler {
    public static void onBeforeUpdate(List<Opportunity> oppList, Map<Id, Opportunity> oldStageMap){
        oppNewStage(oppList, oldStageMap);
    }
	
    public static void oppNewStage(List<Opportunity> oppList, Map<Id, Opportunity> oldStageMap){
        for(Opportunity opp : oppList){
            //Compare the old stage status and new stage status.
            Opportunity oldOppID = oldStageMap.get(opp.Id);           
                if(oldOppID.StageName !=opp.StageName){
                    if(opp.StageName == 'Closed Won'){
                        opp.Description = 'This Opportunity is Closed Won.';
                    }                    
                }           
        }
    }
}
And Trigger is:
trigger OpportunityTrigger on Opportunity (before update) {
    if(Trigger.isBefore)
    {        
        if(Trigger.isUpdate){
            OpportunityTriggerHandler.onBeforeUpdate(Trigger.new, Trigger.oldMap);
        }
    }
}

Thank you!