简体   繁体   English

模拟一个无效方法-这是正确的吗?

[英]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. 如果'message'中的XML无效,validate()方法将引发异常。

I need 2 tests, one that fails validation and one that passes. 我需要2个测试,其中一项未通过验证,另一项通过了。 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. 看起来您正在尝试使用模拟对象测试XMLSupport.validate()方法并期望它引发异常,要实现此目标,您不能使用Mock XmlSupport对象,如果可能,请创建一个正确的XMLSupport对象并对其进行测试,它应该工作,否则,如果您必须使用Mocked XMLSupport,则需要为XMLSupport提供另一个给定的条件,以显式引发异常,但是我看不出进行这种测试的意义。

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)));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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