Search code examples
javaspringunit-testingswitch-statementtry-catch

How to testing switch-case if the all case return "error" string?


I use JUnit and Mockito. I have a method, who contain switch-cases in a try-catch statement. The all cases return 'null' pojo, but this is not problem, because I know which pojo (=case) returned them. But the try-catch block catching returned error, like this the final return is a "error" string. So I can't explain, who "case" dropped the "error" string. That way I can't find out if the call was made in the right direction, even though that would be the job.

The code sketch:

try{
switch (String str):
    case "a":
        return mapper.writeValueAsString(sampleService.sampleServiceMethod(samplePojo));
    ...
} catch () {
    return DefaultMethodResult.error.name()
}

Solution

  • In my practice, you can define a case value, and you can get the case value when have exception, like this:

    try {
    int caseValue = 1; // replace with actual case value
    switch (caseValue) {
        case 1:
            // code for case 1
            break;
        case 2:
            // code for case 2
            break;
        // add more cases as needed
        default:
            // default case code
        }
    } catch (Exception e) {
        System.out.println("Exception occurred in case: " + caseValue);
    }
    

    Hope to solve you doubts.