Search code examples
muleanypoint-studiomunit

How to write a test case for negative scenario(exception scenario) in munit..?


There is flow which is going to call http-outbound endpoint. I want to write test case for the scenario if http is not available(catching the exception in flow and working as expected from POSTMAN). I tried using throw an exception for mocking the exception to be thrown when message process is http:request.. but it didn't worked. Can someone please help how to mock exception in munit?

Below is the code which i tried:

    <munit:test name="test-project-test-suite-munit-testFlowTest3" description="Test" >
    <mock:when messageProcessor="mule:set-payload" doc:name="Mock">
        <mock:with-attributes>
            <mock:with-attribute name="doc:name" whereValue="#['Set Payload']"/>
        </mock:with-attributes>
        <mock:then-return payload="#['payload3']"/>
    </mock:when>
    <mock:when messageProcessor="mule:flow" doc:name="Mock">
        <mock:with-attributes>
            <mock:with-attribute name="name" whereValue="#[matchContains('munit-testFlow2')]"/>
        </mock:with-attributes>
        <mock:then-return payload="#[]">
            <mock:invocation-properties>
                <mock:invocation-property key="variable2" value="#['response2']"/>
            </mock:invocation-properties>
        </mock:then-return>
    </mock:when>
    <mock:throw-an exception-ref="#[new org.mule.api.MessagingException()]" whenCalling="http:request" doc:name="Throw an Exception">
        <mock:with-attributes>
            <mock:with-attribute name="doc:name" whereValue="#['HTTP-RES']"/>
        </mock:with-attributes>
    </mock:throw-an>
    <flow-ref name="munit-testFlow" doc:name="munit-testFlow"/>
    <munit:assert-payload-equals message="oops failed" expectedValue="#['error-response']" doc:name="Assert Payload"/>
 </munit:test>

Solution

  • Instead of using new org.mule.api.MessagingException() use like below

    new IllegalArgumentException('messaging exception') or

    new java.lang.Exception("messaging exception")

    org.mule.api.MessagingException() is a protected function might not able to use in the way may be. Actually it comes under org.mule.api.MuleException() which is again protected.

    https://www.mulesoft.org/docs/site/3.3.0/apidocs/org/mule/api/MessagingException.html

    Please refer the below url for more details.

    https://forums.mulesoft.com/questions/44929/munit-throw-exception-mock-not-working.html

    working code

    <munit:test name="sample-test-suite-sampleFlowTest" description="Test">
        <mock:throw-an exception-ref="#[new java.lang.Exception('messaging exception')]" whenCalling="http:request" doc:name="Throw an Exception">
        </mock:throw-an>
        <flow-ref name="sampleFlow" doc:name="sampleFlow"/>
        <logger level="INFO" doc:name="Logger"/>
    </munit:test>