Node.getChild(): method to get a child or throw an exception if not found
This commit is contained in:
parent
04599861c0
commit
f95029d348
3 changed files with 39 additions and 0 deletions
|
@ -125,6 +125,16 @@ public interface Node<T> {
|
|||
*/
|
||||
Optional<Node<T>> findChild(T child);
|
||||
|
||||
/**
|
||||
* Fetches the node for the child if present.
|
||||
*
|
||||
* @param child the child's data to search for
|
||||
*
|
||||
* @return the child node if found
|
||||
*
|
||||
* @throws NodeException if the node is not found
|
||||
*/
|
||||
Node<T> getChild(T child);
|
||||
|
||||
/**
|
||||
* Checks if the node is an ancestor.
|
||||
|
|
|
@ -246,6 +246,14 @@ public class NodeItem<T> implements Node<T> {
|
|||
.findAny();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node<T> getChild(final T child) {
|
||||
Optional<Node<T>> optional = findChild(child);
|
||||
if (optional.isPresent())
|
||||
return optional.get();
|
||||
throw new NodeException("Child not found");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the node is an ancestor.
|
||||
*
|
||||
|
|
|
@ -901,4 +901,25 @@ public class NodeItemTest {
|
|||
assertThat(child.getParent()).isSameAs(node);
|
||||
assertThat(node.getChildren()).containsExactly(child);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void canGetChildWhenFound() {
|
||||
//given
|
||||
node = new NodeItem<>("data");
|
||||
Node<String> child = new NodeItem<>("child data", "child name", node);
|
||||
//when
|
||||
Node<String> found = node.getChild("child data");
|
||||
//then
|
||||
assertThat(found).isSameAs(child);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void canGetChildWhenNotFound() {
|
||||
//given
|
||||
exception.expect(NodeException.class);
|
||||
exception.expectMessage("Child not found");
|
||||
node = new NodeItem<>("data");
|
||||
//when
|
||||
node.getChild("child data");
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue