簡體   English   中英

如何使用Java Mockito 1.10.19測試構建器方法

[英]How can I test a builder method using Java Mockito 1.10.19

public class MyXML {
    private MessageParser messageParser;
    private String valueA;
    private String valueB;
    private String valueC;

    public MyXML (MessageParser messageParser) {
        this.messageParser=messageParser;
    }

    public void build() {
        try {
            setValueA();
            setValueB();
            setValueC();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setValueA() {
        valueA = messageParser.getArrtibuteUsingXPath("SomeXPath1...");
    }

    private void setValueB() {
        valueB = messageParser.getArrtibuteUsingXPath("SomeXPath2...");
    }

    private void setValueC() {
        valueC = messageParser.getArrtibuteUsingXPath("SomeXPath...");
    }

    public String getValueA() {
        return valueA;
    }

    public String getValueB() {
        return valueB;
    }

    public String getValueC() {
        return valueC;
    } 
}

因此,我需要使用Mockito來測試生成器方法。 對Mockito來說,我還很陌生,有人可以給我一些示例代碼來說明如何為builder方法編寫測試嗎?

如果您想提出任何建議,可以更改類的設計或使其更易於測試,請告訴我。

要測試build(),您可以嘗試:

@RunWith(MockitoJUnitRunner.class)
public class YourTest {
    @Mock
    private private MessageParser messageParserMock;

    // this one you need to test
    private MyXML myXML;

    @Test
    public void test() {
        myXML = new MyXML(messageParserMock);

        // I believe something like this should work
        Mockito.doAnswer(/* check mockito Answer to figure out how */)
            .when(messageParserMock).getArrtibuteUsingXPath(anyString());
        // you should do this for all your 3 getArrtibuteUsingXPath because setValueA(), setValueB(), setValueC() are called that one and then call build and verify results

        myXML.build(); // for instance
        assertEquals("something you return as Answer", myXML.getValueA());
    }
}

資源https://static.javadoc.io/org.mockito/mockito-core/2.8.9/org/mockito/Mockito.html#stubbing_with_exceptions可能有用-它描述了如何對void方法調用進行存根。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM