0

I can't cover the catch part.Can anyone give some advice?Thanks!

Apex Class

 global static CallInResult queryPhoneCity(String phoneNo){
    //System.debug(phoneNo);
    CallInResult result= new CallInResult();
    try{
        result.msg = CTIUtilities.getPhoneCity(phoneNo);
        result.status = '1';
    }catch(exception e){
        result.status = '-1';
        result.msg = 'unknown';
    }
    return result;
}

Test class

static testMethod void queryPhoneCityTest() {
    String phonestr = '18978655567';
    String phonestr1 = '';
    CallInCTIController_PRD.queryPhoneCity(phonestr);
    CallInCTIController_PRD.queryPhoneCity(phonestr1);
}
enter code here
  • try CallInCTIController_PRD.queryPhoneCity(null); – Himanshu Nov 10 '17 at 8:01
  • I tried but it didn't work.But it still can't cover the catch part. – Chopin Chuong Nov 10 '17 at 9:10
3

Without seeing CTIUtilities, we can't say for certain. At minimum, you could reduce the uncovered amount by reorganizing your code:

global static CallInResult queryPhoneCity(String phoneNo){
    CallInResult result= new CallInResult();
    result.status = '-1';
    result.msg = 'unknown';
    try{
        result.msg = CTIUtilities.getPhoneCity(phoneNo);
        result.status = '1';
    }catch(exception e){
    }
    return result;
}

If CTIUtilities cannot throw an exception, remove the try-catch block. If it can throw an exception, but you can't make it do so, then you'll have to live with less than 100% coverage, which is acceptable.

The reason why we are required to have 75% coverage and not 100% coverage is that you cannot cover all possible code all the time.

I'd like to challenge you to try breaking the code outside of the unit test. Remove the try-catch block, throw a bunch of different things at the method, and see if you can break it. Null values, weird symbols, really long strings, etc. If nothing breaks it, leave the try-catch out. If it does break, you'll know which exception to catch.

Try to avoid catching Exception. It's basically saying "I don't know what can possibly go wrong with my code, so I'm going to ignore all possible errors." This is often harder to diagnose than just letting the exception cause a stack trace. You specifically return an error value of "unknown." That is going to be hard to diagnose later when something does break.

| improve this answer | |

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.