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相当新,有人可以给我一些示例代码,说明我如何编写构建器方法的测试吗?
如果您想建议我改变班级设计或让考试更容易让我知道。
答案 0 :(得分:0)
要测试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方法调用。