You need to sign in to do that
Don't have an account?
Stephen.lordson
How to write test class for both 'If 'and 'Else' statements
In the below code, the code coverage is only 66% . it is covering for try and catch block but not covering for IF AND ELSE block . I am looking for your help
complete code.
--------------
public class MyClassTest{
complete code.
--------------
public class MyClassTest{
public String accountName{get;set;}
public void aMethod(){
try{
Account a = [SELECT id FROM Account WHERE name = :accountName];
if(a.Id=='2'){
accountName = 'A name that I know ';
}else{
accountName = 'A name ';}
} catch (System.queryException e){
accountName = 'A name that I know doesn\'t exist in my real dataset';
}
}
public static testMethod void testAMethod1(){
test.startTest();
MyClassTest mc = new MyClassTest();
mc.accountName = 'A name that I know doesn\'t exist in my real dataset';
mc.aMethod();
List<Account> a = [SELECT id FROM Account WHERE name = 'A name that I know doesn\'t exist in my real dataset'];
System.assert(a.size()>0);
test.stopTest();
}
}
You will have to set mc.accountName to 'A name that I know', then call mc.aMethod() (where 'A name that I know' is a valid account name that matches the correct ID), then set accountName to 'A name' (where the name is an account name that does not match that ID).
Hi,
You have to made some changes in your code also.. here is your test class
important :
Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.
Thanks,
Hitesh Patel
Hi Hitesh,
Thanks for the code. Yeah i know its failing but my intention is to make code coverage 100%
i just copy pase your code and run test. It has passed but the code coverage still 72% . same if ,else block not under coverage. Please advice
Code Coverage 72% (8/11)
Hi,
Here is the code for 87% but to complete 100% you have to remove hard coded id. and replace it with variables
important :
Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.
Thanks,
Hitesh Patel