Skip to content
Advertisement

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

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)

Advertisement

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement