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
Ram S 49Ram S 49 

Hi I want to write a test case for a method which throws custom exception, how can i achieve.

Method containing custom exception
/*
public static decimal CelsiusToKelvin (decimal degree)
    {
        if(degree<-273.16)
        { result = -273.16;
           throw new InvalidDataException('Value cannot be less than -273.16');
        }
}

*/

My Test method
class TemperatureTest {
@isTest static void testCelsiusToKelvin()
{
//What to do here?
}
}
 
lnallurilnalluri
@Ram

In your test method write something like this with your class name
 
SampleClass.CelsiusToKelvin(-300);

This is the sample class i have tried and it has 100% coverage.

SampleClass
 
public class SampleClass {
    public static decimal CelsiusToKelvin (decimal degree)
    {
        Decimal result=0;
        try{
        if(degree<-273.16)
        { 
            result = -273.16;
            throw new ArihantException('Value cannot be less than -273.16');
        }
        }catch(Exception e){
            
        }
        return result;
    }
}

SampleClassTest
 
@isTest
public class SampleClassTest {
    @isTest static void testTemp(){
        SampleClass.CelsiusToKelvin(-300);
    }
}

Let me know if you have other questions. If this works for you mark this reply as best answer.

Thanks.
​​​​​​​
 
Ram S 49Ram S 49
Hi, 
lnalluri, thnk for your reply, How will you check this test class passed using System.assertion.
bcz I am getting error, as the method CelsiusToKelvin() will return the exception.

System.assertEquals(//what to do);
Ram S 49Ram S 49
Hi pls help with the above program, how can i write a negative test case. 
How to check if custom exception have been thrown? using system.assert methods.
 
Singh PraveenSingh Praveen
Hi @Ram you can use a boolean flag for testing and asserts in test class
I'm attaching a sample code for the same 
public class SampleClass {
    public Boolean flag = false;
    public decimal CelsiusToKelvin (decimal degree)
    {
        
        Decimal result=0;
        try{
            if(degree<-273.16)
            { 
                result = -273.16;
                throw new CustomException('Value cannot be less than -273.16');
            }
        }catch(Exception e){
            flag = true;
        }
        return result;
    }
}
Sample Test class for the same
@isTest
public class SampleClassTest {
    @isTest static void testTemp(){
        SampleClass obj = new SampleClass();
        obj.CelsiusToKelvin(-300);
        System.assertEquals(true,obj.flag);
    }
}

Hope this will help if yes then give a thumbs up.