I am unable to test the below mentioned method in JUnit testcase and getting ClassCastException

147 views Asked by At

For below method i am writing JUnit testcase for sonarqube coverage.

    @Transformer
    public Object errorUnWrapper(Message<?> message) {
        String value = "";
        try {
            if (!errorFlag) {               
                value = errorTransform(ESBConstants.SYSTEMERRCODE, ESBConstants.SYSTEMERROR, ESBConstants.SYSTEMTEXT);
                
            } else {                
                value = getbankholiday.getErrorMessage();
            }
        } catch (Exception e) {
            getbankholiday.getE2EObject().logMessage("3005", "Error Occurred in error unwrapper");          
            value = ESBConstants.SYSTEMERRORXML;            
        }
        MessageHeaders headers = ((MessagingException) message.getPayload()).getFailedMessage().getHeaders();
        return MessageBuilder.withPayload(value).copyHeaders(message.getHeaders())
                .copyHeadersIfAbsent(headers).setHeader(ESBConstants.CONTENTTYPE, ESBConstants.CONTENTVALUE)
                .build();
    }

JUnit testcase:

@Test
    void testErrorUnWrapper() throws IOException {
        String xml = FileUtils.readFileToString(new File("src/test/resources/JunitTestCases/input/TC02_wltRequest.xml"),
                "UTF-8");
        test = MessageBuilder.withPayload(xml).build();
        errorTransform.errorUnWrapper(test);
        Assertions.assertTrue(true);
    }

but, unable to mock or test the below line in JUnit testcase.

MessageHeaders headers = ((MessagingException) message.getPayload()).getFailedMessage().getHeaders();

Exception:

java.lang.ClassCastException: java.lang.String cannot be cast to org.springframework.messaging.MessagingException
    at com.bt.or.esb.exceptions.ErrorTransform.errorUnWrapper(ErrorTransform.java:75)
    at com.bt.or.esb.exceptions.ErrorTransformTest.testErrorUnWrapper(ErrorTransformTest.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2

There are 2 answers

0
Simon On BEST ANSWER

Your productive code

(MessagingException) message.getPayload()

means you expect message.payload to be a MessagingException. But in your test, you create

MessageBuilder.withPayload(xml).build()

so payload will be a string. You need to build a message with a MessagingException as payload.

1
Rajani Karuturi On

This usually means you need to refactor. except for value everything else is common in if else and catch blocks

why don't you compute value first and then execute below two lines?

MessageHeaders headers = ((MessagingException) message.getPayload()).getFailedMessage().getHeaders();
return MessageBuilder.withPayload(value).copyHeaders(message.getHeaders()).copyHeadersIfAbsent(headers)
                    .setHeader(ESBConstants.CONTENTTYPE, ESBConstants.CONTENTVALUE).build();