在for循环中使用模拟对象List获取NullPointerException

时间:2015-05-22 12:47:12

标签: java junit mockito

要模拟的函数是类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中的工作方式。有没有解决方法呢?

1 个答案:

答案 0 :(得分:4)

您需要将mockNodes添加到setup方法中的列表中。

@Before
public void setup() throws Exception
{
    mockListOfNodes = Arrays.asList(mockNode, mockNode, mockNode);
    when(mockN.getListofNodes()).thenReturn(mockListofNodes);  
}