如何使用 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 方法调用。

相关内容

  • 没有找到相关文章

最新更新