要模拟的函数是类NegotiateNode
:
protected String getAttributeValueFromNodeOfServiceType(String serviceType, String attributeName) {
String attributeValue = null;
for (Node node : this.getListOfNodes()) {
if (node.getServiceType().equals(serviceType)) {
attributeValue = node.getAttribute(attributeName);
break;
}
}
return attributeValue;
}
这是测试:
@Mock private NegotiateNode mockN;
@Mock private Node mockNode;
private List<Node> mockListOfNodes = Arrays.asList(mockNode, mockNode, mockNode);
@Before
public void setup() throws Exception
{
when(mockN.getListofNodes()).thenReturn(mockListofNodes);
}
@Test
public void getAttributeValueFromNodeOfServiceType_ServiceTypeExists_ReturnAttribute() {
when(mockNode.getServiceType()).thenReturn("PMN", "AMC", "SMC");
when(mockNode.getAttribute(anyString()).thenReturn("mockedValue");
when(NegotiateNode.getAttributeValueFromNodeOfServiceType(anyString(), anyString())).thenCallRealMethod();
assertEquals("mockedValue", mockN.getAttributeValueFromNodeOfServiceType("AMC", "dummyAttribute"));
}
我正在运行此测试NullPointerException
。原因是节点的for循环值内部为null
。这似乎是因为List
在java中的工作方式。有没有解决方法呢?
答案 0 :(得分:4)
您需要将mockNodes添加到setup方法中的列表中。
@Before
public void setup() throws Exception
{
mockListOfNodes = Arrays.asList(mockNode, mockNode, mockNode);
when(mockN.getListofNodes()).thenReturn(mockListofNodes);
}