1

I am trying to write a test class for the Apex controller but I am receiving below error. "System.MathException: Divide by 0"

Apex Controller:

public class controller{

public Id accountId{get;set;}    

public Integer getStatusNew() {        
    Integer count1 = 0;        
    count1 = [SELECT count() FROM Account WHERE Status__c = 'New' AND change_date__c = LAST_WEEK ];
    return count1;              
}    
public Integer getStatusProcess() {        
    Integer count2 = 0;        
    count1 = [SELECT count() FROM Account WHERE Status__c = 'Process' AND change_date__c = LAST_WEEK ];
    return count2;              
}
public Integer getStatusOld() {        
    Integer count3 = 0;        
    count1 = [SELECT count() FROM Account WHERE Status__c = 'Old' AND change_date__c = LAST_WEEK ];
    return count3;              
}
//I have updated change_date__c to LAST_N_WEEKS:2 and added three more statuses

public double getcountNew(){   //And I have added three more methods for other statuses with similar Logic
    double c1 = 0;
    double c2 = 0;        
    c1 = [SELECT count() FROM Account WHERE Status__c = 'New' AND change_date__c = LAST_WEEK ];
    c2 = [SELECT count() FROM Account WHERE Status__c = 'New' AND change_date__c = LAST_N_WEEKS:2 ];        
    return (((c1 - c2)/c2)/100);
    }
     public string getDate1(){
        Date d = System.Today();
        Datetime dt = d.toStartofWeek() - 7;
        String LastWeek = dt.format('MM-dd-yyyy');        
return LastWeek ;}    
}
}

I had to follow this approach because my VisualForce component output is a table

status     Last week(date)                 Last two weeks(date)     Percentage
New        Count of acc wid this status     count                    calculation result
Old          count              count                    calculaion Result
Process      count              count                    calculaion Result

Test Class:

@isTest()
private class Controller_test{

static testMethod void getStatus(){        
    Account acc= new Account(Name='Test', Status__c='New' );
//Inserted accounts with all the statuses        
    insert acc;


    partnerStatus classObject = new partnerStatus();
    classObject.accountId = acc.Id;

    Integer newStatus = classObject.getStatusNew();
    //added variables for all the statuses
    Double count1 = classobject.getCountNew(); //Error

    //added assert for all variables
    system.assertNotEquals(0, count1); // Error
    system.assertNotEquals(1, newStatus);  
}
}

I am using this controller in apex component, to display the Percentage of the count, and to get the Last week date in the component. I am unable to test the getcountNew() and getDate1() methods. How can I add this is in test class. Thanks.

Modified Test class:

@isTest()
private class Controller_test{

 static testMethod void getStatus(){        
Account acc= new Account(Name='Test', Partner_Lead_Status__c='New' , Lead_status_change_date__c = Date.today().addDays(-3));
Account acc2= new Account(Name='Test2', Partner_Lead_Status__c='Prospect', Lead_status_change_date__c = Date.today().addDays(-9));    
insert acc;
insert acc2;

partnerStatus classObject = new partnerStatus();
classObject.accountId = acc.Id;
classObject.accountId = acc2.Id;    
Integer newStatus = classObject.getStatusNew();
Double calResult = classobject.getCountNew();
system.assertNotEquals(0, calResult);
system.assertNotEquals(1, newStatus);  
}
}

and my code looks very lengthy as well, can you guide me if there is any other way to write this code. Thanks!

1
  • 1
    You test brought out an issue in your code. Fixing the test to pass will not resolve the issue that was uncovered and is a good case for why tests are written. You need to account for the count remaining 0. Then you can go outs on why it was 0 - you did not set the field that was used in the criteria for your query. You should keep the current test as a negative case test and start a new method setting the values for a positive case test
    – Eric
    Dec 16, 2017 at 8:26

1 Answer 1

1

In your test class you insert an account, but that account isn't included in the the count for the last two weeks. This is because the last n weeks is defined as:

For the number n provided, starts 00:00:00 of the last day of the previous week and continues for the past n weeks.

As Eric point out, you only need to set the change dates to the correct dates and then this should be resolved.

-- Update

The reason for your error is because you query the number of accounts, but there are none and therefore the result is 0. That's okay, except that you end up dividing by 0 after that and that leads to an error. Before you divide the count results in the getcountNew() method I would suggest you check if c2 isn't 0. (Also, you may wish to change the name of that method to better describe what it does.) Depending on your use case the division by 0 might never happen in production and in that case it could be acceptable to just make sure that your test class works correctly. To do that you'd need to create two different accounts and set the created dates at the right intervals.

Account a1 = new Account(Name='3 day old account', Status__c = 'New', Change_date__c = Date.today().addDays(-3) );
insert a1;

Account a2 = new Account(Name='9 day old account', Status__c = 'New', Change_date__c = Date.today().addDays(-9) );
insert a2;

Double calculationResult = classobject.getCountNew(); 

I haven't tried this code, but I hope it will help you resolve this.

12
  • There is a method in the system.test class that allows you to set the createdDate. developer.salesforce.com/docs/atlas.en-us.apexcode.meta/…. In this case however the OP only needs to set the value of the change date field as that is what is used in the query.
    – Eric
    Dec 16, 2017 at 8:21
  • But i need to calculate Last two weeks data as well. Is there any other way to query that? Could you please modify my code and edit the test class.
    – Lin
    Dec 17, 2017 at 0:32
  • Thanks for the explanation Kasper. Now I understood why I am receiving that error. I am completely new to these concepts, hence trying to understand. I have updated the test class by inserting two accounts as you said but I am still receiving the same error. And also let me post my entire code in the Question, coz it looks very lengthy. could you please help me with that as well.
    – Lin
    Dec 17, 2017 at 2:50
  • 1
    I think what Eric wants you to understand is that in programming it is always good to keep in mind the edge cases. In this case it is both possible and not much work to keep in mind your specific edge case and therefore he suggests you fix it correctly. The basic problem you run into is that you can not divide a number by zero. If you try this on a calculator it will return either error, not a number, or something similar. That's why when programming, you should always consider if a variable can be zero, and if so make sure you don't divide by that number before you've checked it's possible.
    – Kasper
    Dec 18, 2017 at 2:57
  • 1
    You can use ROUND(variable, number of digits) for that. You'd get {!ROUND(((statusNew - statusNew2)/statusNew2)/100, 4)}
    – Kasper
    Dec 18, 2017 at 5:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .