简体   繁体   中英

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

So I need to use Mockito to test the builder method. Im fairly new to Mockito could someone give me some example code as to how I might write a test for the builder method?

If you want to suggest any ways I might change the design of the class or make it easier to test let me know.

To test build() you can try :

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

The resource https://static.javadoc.io/org.mockito/mockito-core/2.8.9/org/mockito/Mockito.html#stubbing_with_exceptions might be useful - it describes how to stub void methods call.

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