简体   繁体   中英

Mocking a void method - is this correct?

I need to unit test the following method. The validate() method throws an exception if the XML inside 'message' is invalid.

I need 2 tests, one that fails validation and one that passes. I have tried the failed test below but it's not working. Can anyone tell me how to do this?

    public Boolean validateXML(Message message, Mediation mediation){

    try{
            mediation.getXMLSupport().validate(message,"mySchema.xsd");
            return true;
        } catch(Exception e) {
            return false;
        }
    }


    @Mock
    private Message message;
    @Mock
    private Mediation mediation;

    @Mock
    XMLSupport xmlSupport;

    @Test
    public void test() {
        given(message.getCurrentPayload()).willReturn(new StringMessage("<MalformedXML/>"));
        given(mediation.getXMLSupport()).willReturn(xmlSupport);

        assertFalse((validationSequence.validateXML(message, mediation)));
    }

It looks like you are trying to test XMLSupport.validate() method with mock objects and expecting it to throw exception, to achieve this you can not use a Mock XmlSupport object, if possible create a proper XMLSupport object and test the same, it should work, else if you have to use Mocked XMLSupport then you need to provide another given for XMLSupport to explicitly throw exception but I dont see the point of having such a test.

private XMLSupport xmlSupport = new XMLSupport();

    @Test
    public void test() {
        given(message.getCurrentPayload()).willReturn(new StringMessage("<MalformedXML/>"));
        given(mediation.getXMLSupport()).willReturn(xmlSupport);

        assertFalse((validationSequence.validateXML(message, mediation)));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM