• Sherwin Betonta
  • NEWBIE
  • 30 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 2
    Replies
I'm new to Apex. I would appreciete if somebody can help me with these codes. I can't seem to cover them on my test class. both else statement were the only one's not covered. 

Delete Contact
public static void processBeforeDeleteTrigger(List<Contact> oldContact, Map<Id, Contact> oldContactMap){
        Id accountRelatedID;
        for(Contact con : oldContact){
            accountRelatedID = con.AccountID;
        }
        Account relatedAccount = [SELECT Id, (SELECT ID FROM Contacts) FROM Account WHERE Id =:accountRelatedID];
        List<Contact> conList = new List<Contact>(relatedAccount.Contacts);
        system.debug('number of contacts' + conList.size());
        if(conList.size()==1){
             //this part is not covered
            oldContact[0].addError('Remaining contact cannot be deleted!');
        }

    }

Test Class
public static void deleteContactTEST() {
        Account newAccount = new Account(Name='Test Account Name');
        insert newAccount;
         List<Contact> newContact = new List<Contact>();
         for (Integer count = 0; count < 50; count++) {
             newContact.add(new Contact (LastName=' Test Contact Name' + count, AccountId = newAccount.Id));
         }
        insert newContact;
        Test.startTest();
         Boolean status = RelatedContactController.deleteContact(newContact[0].id);
        Test.stopTest();
         
         List<Contact> getContact = [SELECT Id FROM Contact WHERE AccountId = :newAccount.Id];
         System.assertEquals ( 49 , getContact.size());
         System.assertEquals ( true , status);
         
     }
Search Account
public static string searchQuery(String searchKey, Integer recordToDisply) {
        String name = '%' + searchKey + '%';
        //String finalString = name.replaceAll('\\p{Punct}', '');
        String soqlInject = String.escapeSingleQuotes(name);
        //String SOQL = 'SELECT Id, Name,(select Id from Contacts) FROM Account WHERE Name LIKE :\'' + soqlInject + '\'' + 'ORDER BY Name LIMIT :recordToDisply';
        List<Object> accountList= new List<Object>();
        //Implement a Search Query with SOQL when conditions are met
        if(searchKey!='' || searchKey != null){
            accountList = [SELECT Id, Name,(select Id from Contacts) FROM Account WHERE Name LIKE : soqlInject ORDER BY Name LIMIT :recordToDisply];
        }
        else{
            //this is not covered
            accountList = [SELECT Id, Name,(select Id from Contacts) FROM Account ORDER BY Name LIMIT :recordToDisply];
        }
        //convert data types into JSON format
        return JSON.serialize(accountList);
    }

Test class:
public static void findByNameTest(){
        Integer count = [select count() from account];
        test.startTest();
        List<Object> test4 = (List<Object>)JSON.deserializeUntyped(AccountContactController.searchQuery('Test',6));
        List<Object> test5 = (List<Object>)JSON.deserializeUntyped(AccountContactController.searchQuery('',30));
        test.stopTest();
        system.assertEquals(6, test4.size());
        system.assertEquals(count, test5.size());
    }

 
I coded my functions on the controller but I realized this is not a best practice to code directly on the controller. I tried transferring them but I get errors. Can somebody help me transfer my codes.

Note I exclude some functions. I already transfered already.
Accountcontroller.js
({
    "doInit": function(component, event, helper) {
        //initializes the component 
        helper.setPagination(component);
        //set data table headers
        component.set('v.columns', [
            { label: 'ACCOUNT NAME', fieldName: 'Name', type: 'text' },
            { label: 'NO. OF CONTACTS', fieldName: 'contacts', type: 'text' }
        ]);
    },
    "selectAccount":function(component,event,helper){
        var row = event.getParam('selectedRows');
        //fire event which shows the related contacts of the account selected
        var appEvent = $A.get("e.c:RelatedContactEvent");
        for(var r in row){
            var accId = row[r].Id;
            appEvent.setParams({
                "accId" : accId
            });
            appEvent.fire();
        }
    },
    "searchQueryChange": function(component, event) {
        var recordToDisply = component.get("v.pageSize");
        var searchKey = component.find("searchKey").get("v.value");
        //create a one-time use instance of the serverQuery action
        var action = component.get("c.searchQuery");
        if(searchKey != '' || searchKey != null){
            //prioritizes first page when searching
            component.set("v.page", 1);
            //dynamic searching
            component.set("v.pages", 1); 
        }
        //call server-side action
        action.setParams({
            "searchKey": searchKey,
            "recordToDisply": recordToDisply
        });
        action.setCallback(this, function(a) {
            let accounts = JSON.parse(a.getReturnValue());
            let accountsWithContacts = [];
            accounts.forEach(item =>{
                let newItem = {};
                             newItem.Name = item.Name;
                             newItem.Id = item.Id;   
                             if(item.Contacts)
            newItem.contacts = item.Contacts.totalSize + '';
            else
                newItem.contacts = '0';
            accountsWithContacts.push(newItem);
            if(searchKey == '' || searchKey == null){
                var page = component.get("v.pageCopy");
                var pages = component.get("v.pagesCopy");
                
                component.set("v.page", page);
                
                component.set("v.pages", pages);
            }
        })
        component.set("v.data", accountsWithContacts);
    });
    //adds the server-side controller action to the queue of actions to be executed
    $A.enqueueAction(action);
    },
    "handleSuccess" : function(component, event, helper) {
        var gotcha = $A.get("$Label.c.AccountCreateSuccess");
        component.set('v.isShowAccountForm', false);
        component.find('notifLib').showToast({
            "variant": "success",
            "title": gotcha
        });
        //refreshes the account table view after creating an account
        $A.get('e.force:refreshView').fire();
        
    },
    "navigate": function(component, event, helper) {
        // this function call on click on the previous page button
        var page = component.get("v.page") || 1;
        // get the previous button label
        var direction = event.getSource().get("v.label");
        // get the select option (drop-down) values.
        var recordToDisply = component.get("v.pageSize");
        // set the current page,(using ternary operator.)
        page = direction === "Previous" ? (page - 1) : (page + 1);
        // call the helper function
        helper.getAccounts(component, page, recordToDisply);
    }
})

ContactController.js.
"onSelectChange": function(component, event, helper) {
        // this function call on the select option change,   
        var page = 1
        var recordToDisply = component.find("recordSize").get("v.value");
        helper.getContacts(component, page, recordToDisply);
    },
   "handleSubmit": function(cmp, event, helper) {
        event.preventDefault();
        var accnt = cmp.get("v.accntId");
        var eventFields = event.getParam("fields");
        eventFields["AccountId"] = accnt;
        cmp.find('contactForm').submit(eventFields);
    },
    "handleSuccess" : function(component, event, helper) {
        var createsuccess = $A.get("$Label.c.ContactCreateSucess");
        component.set('v.isShowContactForm', false);
        component.find('notifLib').showToast({
            "variant": "success",
            "title": createsuccess
        });
        //refreshes the contact table view after creating a contact
        $A.get('e.force:refreshView').fire();
    },  
    "handleRowAction" : function (component, event, helper) {
        var action = event.getParam('action');
        var row = event.getParam('row');
        console.log("ACTION NAME: " + action.name);
       
        switch (action.name) {
            case 'view':
                var navEvt = $A.get("e.force:navigateToSObject");
                navEvt.setParams({
                      "recordId": row.Id,
                      "slideDevName": "details"
                    });
                navEvt.fire();
                break;
               
            case 'delete':
               var doAction = component.get("c.deleteContact");
              
               doAction.setParams({
                    "Id": row.Id
                });
                doAction.setCallback(this,function(response){
                    // store the response return value
                    var resultData = response.getReturnValue();
                    var state = response.getState();
                    var delsuccess = $A.get("$Label.c.ContactDeleteSuccess");
                    var delfail = $A.get("$Label.c.ContactDeleteFail");
                    if (state == "SUCCESS") {
                        if(resultData == true){
                            component.find('notifLib').showToast({                               
                                "variant": "success",
                                "title": delsuccess
                               });
                            $A.get('e.force:refreshView').fire();
                        }else{
                            component.find('notifLib').showToast({
                                "variant": "error",
                                "title": delfail
                               });   
                        }
                    }
                    
                });
                $A.enqueueAction(doAction);
                break;
        }
    },
    "navigate": function(component, event, helper) {
        // this function call on click on the previous page button  
        var page = component.get("v.page") || 1;
        // get the previous button label  
        var direction = event.getSource().get("v.label");
        // get the select option (drop-down) values.  
        var recordToDisply = component.get("v.pageSize");
        // set the current page,(using ternary operator.)  
        if(direction == "Previous"){
            page = (page - 1);
        }else{
            page = (page + 1);
        }
        component.set("v.page", page);
        // call the helper function
        helper.getContacts(component, event, page, recordToDisply);
    },

 
Can somebody help me with my code. I created a negative test for Helper Class  to cover the catch block but it's still not successfully covered.

This is my helper class:
public with sharing class AccOppRecalcHelperClass {
    
    //A method which will be called in the trigger
    public static void opportunityTriggerMethod(List<Opportunity> oppList, Map<Id,Opportunity> oldOpp){
        
        //instantiate a list of ID's to store id's of account records
       List<id> accId = new List<id>();
        //instantiate a list of accounts
       List<account> acc = new List<account>();
        //initialize string variable closedWon to Closed Won stage field value stored in custom label
        String Closed_Won = Label.Closed_won;
        //initialize string variable closedLost to Closed Lost stage field value stored in custom label
        String Closed_Lost = Label.Closed_lost;
        String oldaccstat;
        String acctstat;
        Integer oppClosedLost = 0;
        Integer oppClosedWon = 0;
        
        //checks opportunity records from opportunity list
       for(Opportunity opp: oppList){
          //checks if account related to opportunity field is not empty
           if(opp.AccountId != NULL){
               //adds account ID related to opportunity record to list of ID's
               accId.add(opp.AccountId); 
           }
             
       }
        for (Opportunity oppRec : [SELECT Id, Name, StageName FROM Opportunity WHERE AccountId IN :accId AND StageName != NULL]){
            if( oppRec.StageName == Closed_Won){
                oppClosedWon++;
               
            }
            else if (oppRec.StageName == Closed_Lost){
                oppClosedLost++;
            }
        }
        for (Account myAccount : [SELECT ID, Number_of_Opportunities_Won__c, Number_of_Opportunities_Lost__c FROM Account WHERE ID in :accId ]){
            
                myAccount.Number_of_Opportunities_Won__c = oppClosedWon;
                myAccount.Number_of_Opportunities_Lost__c = oppClosedLost;
                acc.add(myAccount);
            
        }
            
        if (acc.size()>0){
            try{
               update acc; 
            }
            catch(Exception e){
                System.debug(e);
            }
        }
        
    } 
}

Here is my negative test method:
@isTest
    private static void negativeTest(){
        List<Account> accts = new List<Account>();
        Account a = new Account(name= 'TestAccount1');
        insert a;
        a.name = 'Sherwin';
        
        Test.startTest();
        accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];

		update a;
       	Test.stopTest();
       	System.assert(accts.size() > 0, 'Was expecting to find at least one account');
        System.assertEquals('Sherwin', a.name);
        }

Thanks in advance.
Good day. How can I cover the catch clock with my current class. I'm stuck at 96% code coverage.
public with sharing class AccOppRecalcHelperClass {
    
    //this method which will be called in the trigger
    public static void opportunityTriggerMethod(List<Opportunity> oppList, Map<Id,Opportunity> oldOpp){
        
        //instantiate a list of ID's to store id's of account records
       List<id> accId = new List<id>();
        //instantiate a list of accounts
       List<account> acc = new List<account>();
        //initialize string variable closedWon to Closed Won stage field value stored in custom label
        String Closed_Won = Label.Closed_won;
        //initialize string variable closedLost to Closed Lost stage field value stored in custom label
        String Closed_Lost = Label.Closed_lost;
        String oldaccstat;
        String acctstat;
        Integer oppClosedLost = 0;
        Integer oppClosedWon = 0;
        
        //checks opportunity records from opportunity list
       for(Opportunity opp: oppList){
          //checks if account related to opportunity field is not empty
           if(opp.AccountId != NULL){
               //adds account ID related to opportunity record to list of ID's
               accId.add(opp.AccountId); 
           }
             
       }
        for (Opportunity oppRec : [SELECT Id, Name, StageName FROM Opportunity WHERE AccountId IN :accId AND StageName != NULL]){
            if( oppRec.StageName == Closed_Won){
                oppClosedWon++;
               
            }
            else if (oppRec.StageName == Closed_Lost){
                oppClosedLost++;
            }
        }
        for (Account myAccount : [SELECT ID, Number_of_Opportunities_Won__c, Number_of_Opportunities_Lost__c FROM Account WHERE ID in :accId ]){
            
                myAccount.Number_of_Opportunities_Won__c = oppClosedWon;
                myAccount.Number_of_Opportunities_Lost__c = oppClosedLost;
                acc.add(myAccount);
            
        }
            
        if (acc.size()>0){
            try{
               update acc; 
            }
            catch(Exception e){
                System.debug(e);
            }
        }
        
    } 
}
This is my test class


 
@isTest
public class AccountOpportunityRecalculationTest {
  
private static testMethod void updateStage(){
    User sysAd = [SELECT Id,Name FROM User WHERE FirstName = 'Sherwin'];
      System.runAs(sysAd) {
         // The following code runs as System Administrator.
         Account[] accts = TestDataFactory.createAccountsWithOpps(1, 1, 'Closed Won');
         // The following code runs as user in Marketing Group.
         User MarketingUser = [SELECT Id,Name FROM User WHERE FirstName = 'Mario'];
         Test.startTest();
          try {
              System.runAs(MarketingUser) {
                    // Query for the opportunity, which has been associated with an account.
                    Opportunity opportunityToUpdate = [SELECT StageName FROM Opportunity 
                                                       WHERE StageName = 'Closed Won' ORDER BY LastModifiedDate DESC NULLS FIRST LIMIT 1];
                  // Update the billing city.
        			opportunityToUpdate.StageName = 'Closed Lost';
                  // Make the update call.
        			update opportunityToUpdate;
                  	System.assertEquals('Closed Lost', opportunityToUpdate.StageName , 'Expected opportunity with Closed Lost stage name');
              }
          
		} catch(Exception e) {
    		System.debug('An unexpected error has occurred: ' + e.getMessage());
	}         	
         }
         Test.stopTest();
        }
}
I'm to new to apex. 
I have a class that would allow Users from a public group (marketing group) to access records created by another user say "System Admin".

I wanted to create a test class that would create a record using the sys admin profile and check if the marketing group can have edit access to the record.

Here is my code: 
public class OpportunitySharing {
    //sharing record after creating
   public void shareAfterInsert(List<Opportunity> oppoList){
       OpportunityShare oppShare = new OpportunityShare();

       List<Group> MarketingGroup = [SELECT Id, Name FROM Group WHERE Name = 'Marketing Group'];

       for(Opportunity opp: oppoList) {
           for(Group mg : MarketingGroup) {
               
               oppShare.OpportunityId = opp.Id;
               oppShare.UserOrGroupId = mg.Id;
               oppShare.OpportunityAccessLevel = 'Edit';
               Database.SaveResult dbsr = Database.insert(oppShare, false);
           }
       }
   }
}

 
I want to sort String values from a custom field from custom settings. I had no issues with the code but I get the error "Method does not exist or incorrect signature: void ascending() from the type anon'

Here's my code:
public class SortNumbersFromCustomSetting {
	static Dev_Bootcamp__c value = Dev_Bootcamp__c.getInstance();
    
    static List<String> ListStringValue = new List<String>(value.Random__c.split('-'));
    
   		public static List<Integer> ascending(){
         List<Integer> ListIntValue = new List<Integer>();
            for(String str:ListStringValue){
                ListIntValue.add(Integer.valueOf(str));
            }
         ListIntValue.sort();
         Set<Integer> SetIntValue = new Set<Integer>(ListIntValue);
         List<Integer> FinalValue = new List<Integer>(SetIntValue);
         return FinalValue;
     }
    public static List<Integer> descending(){
        List<Integer> Temp = ascending();
        List<Integer> DescIntValue = new List<Integer>();
        for(Integer i = Temp.size()-1; i>=0; i--){
            DescIntValue.add(Temp.get(i));
        }
        return DescIntValue;
    }
}

 
Can somebody help me with my code. I created a negative test for Helper Class  to cover the catch block but it's still not successfully covered.

This is my helper class:
public with sharing class AccOppRecalcHelperClass {
    
    //A method which will be called in the trigger
    public static void opportunityTriggerMethod(List<Opportunity> oppList, Map<Id,Opportunity> oldOpp){
        
        //instantiate a list of ID's to store id's of account records
       List<id> accId = new List<id>();
        //instantiate a list of accounts
       List<account> acc = new List<account>();
        //initialize string variable closedWon to Closed Won stage field value stored in custom label
        String Closed_Won = Label.Closed_won;
        //initialize string variable closedLost to Closed Lost stage field value stored in custom label
        String Closed_Lost = Label.Closed_lost;
        String oldaccstat;
        String acctstat;
        Integer oppClosedLost = 0;
        Integer oppClosedWon = 0;
        
        //checks opportunity records from opportunity list
       for(Opportunity opp: oppList){
          //checks if account related to opportunity field is not empty
           if(opp.AccountId != NULL){
               //adds account ID related to opportunity record to list of ID's
               accId.add(opp.AccountId); 
           }
             
       }
        for (Opportunity oppRec : [SELECT Id, Name, StageName FROM Opportunity WHERE AccountId IN :accId AND StageName != NULL]){
            if( oppRec.StageName == Closed_Won){
                oppClosedWon++;
               
            }
            else if (oppRec.StageName == Closed_Lost){
                oppClosedLost++;
            }
        }
        for (Account myAccount : [SELECT ID, Number_of_Opportunities_Won__c, Number_of_Opportunities_Lost__c FROM Account WHERE ID in :accId ]){
            
                myAccount.Number_of_Opportunities_Won__c = oppClosedWon;
                myAccount.Number_of_Opportunities_Lost__c = oppClosedLost;
                acc.add(myAccount);
            
        }
            
        if (acc.size()>0){
            try{
               update acc; 
            }
            catch(Exception e){
                System.debug(e);
            }
        }
        
    } 
}

Here is my negative test method:
@isTest
    private static void negativeTest(){
        List<Account> accts = new List<Account>();
        Account a = new Account(name= 'TestAccount1');
        insert a;
        a.name = 'Sherwin';
        
        Test.startTest();
        accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];

		update a;
       	Test.stopTest();
       	System.assert(accts.size() > 0, 'Was expecting to find at least one account');
        System.assertEquals('Sherwin', a.name);
        }

Thanks in advance.
I'm to new to apex. 
I have a class that would allow Users from a public group (marketing group) to access records created by another user say "System Admin".

I wanted to create a test class that would create a record using the sys admin profile and check if the marketing group can have edit access to the record.

Here is my code: 
public class OpportunitySharing {
    //sharing record after creating
   public void shareAfterInsert(List<Opportunity> oppoList){
       OpportunityShare oppShare = new OpportunityShare();

       List<Group> MarketingGroup = [SELECT Id, Name FROM Group WHERE Name = 'Marketing Group'];

       for(Opportunity opp: oppoList) {
           for(Group mg : MarketingGroup) {
               
               oppShare.OpportunityId = opp.Id;
               oppShare.UserOrGroupId = mg.Id;
               oppShare.OpportunityAccessLevel = 'Edit';
               Database.SaveResult dbsr = Database.insert(oppShare, false);
           }
       }
   }
}