function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MedhanieHabteMedhanieHabte 

Getting to 100 percent code coverage on my trailhead module “Write Negative Tests Unit”

I seem to be stuck on this trailhead module or write negative tests unit, while I have 93 percent code coverage, I can't seem to get the code coverage to hit 100 percent at the "returnValue" piece doesn't seem to hit.
My code is as follows.

Calculator Class
 
public class Calculator {
 public class CalculatorException extends Exception{}

  public static Integer addition(Integer a, Integer b){
   return a + b;
    }

   public static Integer subtraction(Integer a, Integer b){
    return a - b;
    }

 public static Integer multiply(Integer a, Integer b){
  if(b==0 || a==0){
  throw new CalculatorException('It doesn\'t make sense to multiply by 
   zero');
  }
  return a * b;
  }

 public static Decimal divide(Integer numerator, Integer denominator){
  if(denominator == 0){
  throw new CalculatorException('you still can\'t divide by zero');
   }
 Decimal returnValue = numerator / denominator;
  if(returnValue < 0){
    throw new CalculatorException('Division returned a negative value.' + 
 returnValue);
 }
   return returnValue;
  }


 }

And my test class as follows
 
@isTest
   public class Calculator_Tests {

@isTest
 public static void addition() {
    Calculator.addition(1, 0);
   }
@isTest
  public static void subtraction() {
    Calculator.subtraction(1, 0);
   }

@isTest
 public static void divide_throws_exception_for_division_by_zero() {
 Boolean caught = false;
 try {
    Calculator.divide(1, 0);
  } catch (Calculator.CalculatorException e) {
    System.assertEquals('you still can\'t divide by zero', e.getMessage(), 
  'caught the right exception');
    caught = true;
   }
   System.assert(caught, 'threw expected exception');
   }

  @isTest
 public static void divide_throws_exception_for_division_by_two() {
 Boolean caught = true;
 try {
    Calculator.divide(1, 2);
 } catch (Calculator.CalculatorException e) {
    System.assertEquals('you still can\'t divide by zero', e.getMessage(), 
  'caught the right exception');
    caught = true;
   }
   System.assert(caught, 'threw expected exception');
 }


@isTest
public static void multiply_by_one() {
  Boolean caught = false;
  try {
    Calculator.multiply(1, 0);
    } catch (Calculator.CalculatorException e) {
    System.assertEquals('It doesn\'t make sense to multiply by zero', 
    e.getMessage(), 'caught the right exception');
     caught = true;
    }
    System.assert(caught, 'threw expected exception');
  }

@isTest
 public static void multiply_by_two() {
  Boolean caught = true;
  try {
     Calculator.multiply(1, 2);
   } catch (Calculator.CalculatorException e) {
    System.assertEquals('It doesn\'t make sense to multiply by zero', 
  e.getMessage(), 'caught the right exception');
    caught = true;
   }
   System.assert(caught, 'threw expected exception');
}   
}

 
Best Answer chosen by MedhanieHabte
Abdul KhatriAbdul Khatri
How come a division returned a negative value with positive numbers? I don't think that is the right Scenario. 

Infact you can change that not accepting the negative value like this 
 
public static Decimal divide(Integer numerator, Integer denominator){
        if(denominator == 0){
            throw new CalculatorException('you still can\'t divide by zero');
        }
        if(numerator < 0 || denominator < 0)
        	throw new CalculatorException('negative value(s) not allowed.');
        
        Decimal returnValue = numerator / denominator;

        return returnValue;
    }

and add another test method
@isTest
    public static void divide_throws_exception_for_negative_number() {
        Boolean caught = true;
        try {
            Calculator.divide(-1, 2);
        } catch (Calculator.CalculatorException e) {
            System.assertEquals('negative value(s) not allowed.',e.getMessage());
            caught = true;
        }
        System.assert(caught, 'threw expected exception');
    }

I hope this will help.​

All Answers

Abdul KhatriAbdul Khatri
How come a division returned a negative value with positive numbers? I don't think that is the right Scenario. 

Infact you can change that not accepting the negative value like this 
 
public static Decimal divide(Integer numerator, Integer denominator){
        if(denominator == 0){
            throw new CalculatorException('you still can\'t divide by zero');
        }
        if(numerator < 0 || denominator < 0)
        	throw new CalculatorException('negative value(s) not allowed.');
        
        Decimal returnValue = numerator / denominator;

        return returnValue;
    }

and add another test method
@isTest
    public static void divide_throws_exception_for_negative_number() {
        Boolean caught = true;
        try {
            Calculator.divide(-1, 2);
        } catch (Calculator.CalculatorException e) {
            System.assertEquals('negative value(s) not allowed.',e.getMessage());
            caught = true;
        }
        System.assert(caught, 'threw expected exception');
    }

I hope this will help.​
This was selected as the best answer
KapavariVenkatramanaKapavariVenkatramana
@Abdul Khatri 

Now We are getting 93 % Code Coverage Only...Is there 100% Code coverage 
Diksha RahangdaleDiksha Rahangdale
Please check the below code for 100% code coverage. I completed my challenge with this code and got 500 points...

 @isTest static void testdivide_WithNegativevalue()
    {
      
        Boolean caught = true;
        try{
          Calculator.divide(-4,2);
        }
        catch(Calculator.CalculatorException e)
        {
            //Always write correct assertion
            System.assertEquals('Division returned a negative value.', e.getMessage());
            caught = true;
                
        }
        system.assert(caught,'threw expected exception');
        
    }
    
I hope this will help you...
Aditya Sharma 114Aditya Sharma 114
Thanks @Abdul ... Worked for me as well.
Bhagwan DasBhagwan Das
Thank for Giving me This Chance.
IPL Match Prediction (http://iplprediction2020x.in/)
Bruno Araujo 2Bruno Araujo 2
Seems fair. You should go here (https://essaydragon.com/blog/how-to-write-hook-for-your-essay) for more code improvements.
Jim KyriacouJim Kyriacou

Just completed the trailhead and thanks to the contributors, as the trailhead wasnt very good at explaining the approach.
You need to get the detail exact, so

if passing Calculator.divide(-2,2);

System.assertEquals('Division returned a negative value.-1', e.getMessage(), 
  'caught the right exception');

if passing Calculator.divide(-4,2);

System.assertEquals('Division returned a negative value.-2', e.getMessage(), 
  'caught the right exception');

 

IPL PredictionIPL Prediction
Thank for Giving me This Chance.
IPL Match Prediction (http://www.iplmatchpredictionastrology.com/)
ipl prediction 9ipl prediction 9
Thanks for sharing this. 
Let's know who won in IPL today (https://www.iplprediction2020.in/)
ipl prediction 9ipl prediction 9
Thanks for this sharing...
IPL Astrology(https://www.todayiplmatchprediction2020.in/)
TonystkTonystk
MPL Mobile Premier League Gaming, MPL Pro Apk Download (https://mplproapp.in/download-mpl-apk-for-android/), MPL App Latest Version Download Apk, MPL Referral Code (https://mplproapp.in/mpl-referral-code/), Refer Code, Invite Code, MOD Apk, Hacked Apk, Free Cash Bonus, Winning Cash, MPL Application Tips And Tricks, Unlimited Tokens, Fantasy Games, MPL Customer Care Number, Add Money Offers, Refer And Earn Unlimited Paytm Cash, Withdraw, Redeem 2021
Ankit Jain 3010Ankit Jain 3010
If you don't mind i would like to ask about this more. How it can be performed? However, If you wish to express Love then share these Hurt Shayari in Hindi- उनका दिया कोई ज़ख्म भरे (https://hindishayarifm.com/category/hurt-shayari/).
Anandmani Rathor 7Anandmani Rathor 7
Negative Assertion is necessary as this challenge is of negative assertion case.
  • Used system.assertNotEquals() 
  • Handled all exceptional cases 

 
@isTest
public class Calculator_Tests {

//positive addition
    @isTest public static void additionTest()
    {
       Integer addition= Calculator.addition(6, 7);
        system.assertEquals(addition,13);
    }

//positive substraction
    @isTest public static void substractionTest()
    {
        Integer substraction= Calculator.subtraction(12, 7);
        system.assertEquals(substraction,5); 
    }

//positive Multiplication
    @isTest public static void PositiveMultiplicationTest()
    {
        Integer multi= Calculator.multiply(12, 7);
        system.assertEquals(multi,84); 
    }


//positive division
    @isTest public static void DivisionTest()
    {
        Decimal div= Calculator.divide(12, 7);
        system.assertNotEquals(div,0);  
    }

​​​​​​​
//multiplication by zero exceptional case
    @isTest public static void multiplicationExceptionTest()
    { 
        List<Boolean> exceptions = new List<Boolean>();
        try{
        Integer multi= Calculator.multiply(12, 0);
           } 
     catch(Calculator.CalculatorException awe){
  {
          if(awe.getMessage().equalsIgnoreCase('It doesn\'t make sense to multiply by zero')){
            exceptions.add(true);
          }
  }   
     
    system.assertNotEquals(null, exceptions, 'expected at least one exception to have occured');}
    }


//Negative Division result exceptional case
        @isTest public static void NegativeResultExceptionTest()
    { 
        List<Boolean> exceptions = new List<Boolean>();
        try{
       Calculator.divide(-12, 3);
           } 
     catch(Calculator.CalculatorException awe){
  
          if(awe.getMessage().equalsIgnoreCase('Division returned a negative value.-4')){
            exceptions.add(true);
          }
  }
           system.assertNotEquals(null, exceptions, 'expected at least one exception to have occured');
     
    }


//Division by zero exceptional case
            @isTest public static void DivisionByZeroExceptionTest()
    { 
        List<Boolean> exceptions = new List<Boolean>();
        try{
       Calculator.divide(12, 0);
           } 
     catch(Calculator.CalculatorException awe){
  {
          if(awe.getMessage().equalsIgnoreCase('you still can\'t divide by zero')){
            exceptions.add(true);
          }
  }
           system.assertNotEquals(null, exceptions, 'expected at least one exception to have occured');}
    }

}
ish maseish mase
Is this possible to use this script for coupons deal project? I'm asking for my dynmaic website. I'm offering the red lobster coupons (https://www.couponladydeals.com/red-lobster-coupons/) on my website.
john pop 2john pop 2
Minecraft is a popular Arcade game with over 100 million monthly active users. The game was recently bought by Microsoft and is currently developed and managed by the company itself. You might face errors and issues if you are using a Microsoft device such as Xbox or Windows. Get more about aka.ms/xboxsetup issues here. https://kinetichifi.com/aka-ms-xboxsetup/
bache madvibache madvi
ressolved my issue blogger at : https://bestoffsetsmoker.net/
feceya maryafeceya marya
I loved reading it. Thanks for sharing all these information, it’s so
appreciated!   Tescoviews