Solved
Unable to Mock Node and Set Properties in JUnit
I have a function to convert node properties to json object and need to unit test that function. But I have tried many ways to mock the node but still getting null value.
public class NodePropertiesImpl{
public JSONObject getNodeProperties(Node node) {
JSONObject nodeJson = new JSONObject();
try {
nodeJson.put("componentGroup", getValueFromProperty(node, "group"));
nodeJson.put("componentTitle", getValueFromProperty(node, "jcr:title"));
nodeJson.put("componentPath", node.getPath());
} catch (Exception ex) {
log.error(ex.getMessage());
}
return nodeJson;
}
public String getValueFromProperty(Node node, String propertyKey) {
String propertyVal = new String();
try {
if(node.hasProperty(propertyKey)){
propertyVal = node.getProperty(propertyKey).getValue().toString();
}
} catch (Exception e) {
log.error(e.getMessage());
}
return propertyVal;
}
}
Here's the unit test:
public class NodePropertiesImplTest extends AbstractTest {
private NodePropertiesImpl nodeImpl;
@Mock
private Node node;
private Resource resource;
private Property property;
@Before
public final void setUp() throws Exception {
nodeImpl= new NodePropertiawImpl();
context.registerInjectActivateService(nodeImpl);
}
@Test
public void WHEN_NodeHasProperties_RETURN_AllNodePropertiesInJSON() throws JSONException, RepositoryException {
//Arrange
Node node = Mockito.mock(Node.class);
node.setProperty("nodeName", "node name is Hello");
node.setProperty("NodePath", "wcm/foundation/components/responsivegrid");
//Act
JSONObject actualJson = nodeImpl.getNodeProperties(node);
//Assert
}
}
The node parameter is null even though the properties are set. I was wondering what's the correct syntax for this?