2

The blue indicates test coverage. The red indicates uncovered code. Where would I find the cause for the uncovered code?

 public List<Opportunity> insertOpportunityAndDefineRelationships(Contact contact, Account currentAccount, Opportunity opportunity) {

        String orgId = UserInfo.getOrganizationId();
        String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
        Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
        String uniqueName = orgId + dateString + randomInt;

        Opportunity ocrPhantomOpp = new Opportunity(External_ID__c = uniqueName);
        opportunity.AccountId = currentAccount.Id; //relate opportunity to the contacts account.
        opportunity.External_ID__c = uniqueName; //this is so that the opportunity that we are about to insert is treated as the same record as the other opportunity variable that we are defining as the parent in the OpportunityContactRole. Note we have to have another variable because otherwise if we did not use the ocrPhantomOpp we would get a DMLException: More than 1 field provided in an external foreign key reference in entity: Opportunity

        OpportunityContactRole ocr = new OpportunityContactRole(contactId=contact.Id, Opportunity = ocrPhantomOpp); //possible pre-insert because use of external id allows relationship of this phantom record
        System.debug('contact.Id: '+contact.Id + ' ' + 'opportunity: ' + opportunity);

            // Create the account and the opportunity.
            Database.SaveResult[] results = Database.insert(new SObject[] {
                opportunity, ocr });

        System.debug(opportunity.Id);
            // Check results.
            for (Integer i = 0; i < results.size(); i++) {
                if (results[i].isSuccess()) {
                System.debug('Successfully created ID: '
                      + results[i].getId());
                } else {
                System.debug('Error: could not create sobject '
                      + 'for array element ' + i + '.');
                System.debug('   The error reported was: '
                      + results[i].getErrors()[0].getMessage() + '\n');
                }
            }

            return [Select Id From Opportunity Where External_ID__c = :uniqueName];
    }

Test Code

//create the page, set to current page, set the controller, put parameters in the page, then call the controller methods.
@isTest
public class OpportunityDynamicVFCtrl_Test {

    @isTest static void testMyController() {
        //start - load framework settings
            //load trigger framework custom settings so that dml succeeds
            TriggerControlFactoryTest.testCreateTriggerControlCustomSettings();

            //start - factory custom setting
                AccountsOwnedLimitPerUser__c mycs = AccountsOwnedLimitPerUser__c.getValues('salesManagementUsersURL');

                if(mycs == null) {
                mycs = new AccountsOwnedLimitPerUser__c(Name= 'salesManagementUsersURL');
                mycs.salesManagementUsersURL__c = 'https://www.test.com';
                insert mycs;
                }
            //end - factory custom setting
        //end - load framework settings

        //Correct business behavior means accessing the page from a button on Contact detail page.
        Account account = (Account)SmartFactory.createSObject('Account');
        //set specific values to pass your custom Validation Rules (didnt work so using ExcludedFields instead ) //this helps dismiss validation rule errors
        account.Account_Engagement_Status_Why_Yellow_Red__c = SmartFactory.DefaultAccountEngagementStatusWhyYellowRedc;//'some reason to pass validation rule on account';
        account.Account_Engagement_Status__c = SmartFactory.DefaultAccountEngagementStatusc;//'Yellow-- Met with- no current opp and no need for BDR engagement';
        insert account;
        System.assert(account.Id != null);
        System.assert(account.Name != null);

        Contact contact = (Contact)SmartFactory.createSObject('Contact');
        contact.accountId = account.Id;
        insert contact;

        Test.startTest();
            PageReference pageRef = Page.OpportunityDynamicVFCtrl; //create the page
            Test.setCurrentPage(pageRef); //set to current page

            OpportunityDynamicVFCtrl controller = new OpportunityDynamicVFCtrl(new ApexPages.StandardController(contact)); //set the controller

            // Add parameters to page URL
            ApexPages.currentPage().getParameters().put('Id', contact.Id);

            // call the constructor
            ApexPages.StandardController sc = new ApexPages.StandardController(contact);

            // Populate controller variables
            //controller.Opportunity = opportunity;
            controller.Contact = contact;
            //controller.currentAccount = null;
            controller.currentAccountList = controller.getCurrentAccountListFromContact(contact);

            controller.save();
            // Verify that the success page displays


        Test.stopTest();
    }
}

enter image description here

5

Code coverage includes the last line that executed. Presumably, you threw an exception here, so the next line remains uncovered. If it failed because of validation, it would be a DMLException, otherwise it could have been something else, the next most likely being a NullPointerException. Keep in mind that the Database methods throw exceptions when a record fails to save unless you specify allOrNone as false:

        Database.SaveResult[] results = Database.insert(new SObject[] {
            opportunity, ocr }, false);
| improve this answer | |
  • i am unable to find the exception. Would i need to trace only the test class? or both the test class and the class it tests? Since the DML is on two sobjects and my goal is to find the exception would i trace the triggers for both objects? dev console > new run > test method shows success and when i download the log no hint of exception – Peter Noges Sep 22 '17 at 19:09
  • @SFDC_peter You should fix your controller first (add the , false, as above), then you can check your results. Your main logic isn't valid as it is. – sfdcfox Sep 22 '17 at 19:11
  • i want all or nothing, why is it invalid as is? – Peter Noges Sep 22 '17 at 19:13
  • 1
    @SFDC_peter Because you're not catching a DMLException but trying to check SaveResult records. Either use allOrNone as false with SaveResult checking, or use a try-catch(DMLException e). – sfdcfox Sep 22 '17 at 19:15
  • 1
    @SFDC_peter There will not be an exception (under normal situations) if you set allOrNone to false. You don't need the try-catch block. You'll need to use something other than debug statements if you want to see coverage. – sfdcfox Sep 22 '17 at 21:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.