0

I wrote a simple class that calculates the amount to discount on a opportunity based on a Discount_Level__c field, which is a picklist with three different values.

Here's the class:

public with sharing class OppDiscountCalculator {

//costruttore
public OppDiscountCalculator() {

}

//given an opportunity, calculates the amount to subtract from the total amount and returns it
public Decimal calculateDiscount(Opportunity myOpp) {

    Decimal discountPercentage = getDiscountPercentage(myOpp);
    Decimal oppAmount = myOpp.Amount;
    Decimal discountAmount = oppAmount * discountPercentage;


    return discountAmount;

}

// given an opportunity, checks the discount level and returns the discount percentage based on that level
public Decimal getDiscountPercentage(Opportunity o) {
    
    Decimal discountPercentage;

    if (o.Discount_Level__c == 'Gold') {
        discountPercentage = 0.30;
    } else if (o.Discount_Level__c == 'Silver') {
        discountPercentage = 0.15;
    } else {
        discountPercentage = 0.05;
    }

    return discountPercentage;

}
}

I am trying to write a test class now and run tests. This is what I wrote:

@isTest
private class OppDiscountCalculatorTest {

@IsTest
static void calculateDiscount(){

    OppDiscountCalculator myCalcObj = new OppDiscountCalculator();

    Opportunity[] myOpp = [SELECT ID, Amount, Discount_Level__c FROM Opportunity WHERE Name='Burlington Textiles Weaving Plant Generator'];

    
    myCalcObj.calculateDiscount(myOpp[0]);
    
}


}

When I try to run the test method, this is wat I get: System.ListException: List index out of bounds: 0 Class.OppDiscountCalculatorTest.calculateDiscount: line 11, column 1 36

enter image description here

I'm new to this and I don't really understand what I am doing wrong. Could someone please give me a detalied explaination? I wanna make sure I understand this deeply

1 Answer 1

3

Test methods do not have access to the data in your org. Therefore your query is not returning any records which results in an empty list. You will need to first create the data in your test method. I recommend you review the documentation for Apex testing. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing.htm https://trailhead.salesforce.com/content/learn/modules/apex_testing

1
  • Thanks very much.
    – robruf
    Mar 28, 2021 at 13:38

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.