gpt4 book ai didi

java - 如何使用 Java Mockito 1.10.19 测试构建器方法

转载 作者:太空宇宙 更新时间:2023-11-04 10:59:45 25 4
gpt4 key购买 nike

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 相当陌生,有人可以给我一些示例代码,告诉我如何为构建器方法编写测试吗?

如果您想建议我改变类的设计或使其更容易测试的任何方法,请告诉我。

最佳答案

要测试 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可能有用 - 它描述了如何 stub void 方法调用。

关于java - 如何使用 Java Mockito 1.10.19 测试构建器方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47019918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com