Node.getChild(): method to get a child or throw an exception if not found

This commit is contained in:
Paul Campbell 2016-05-24 14:39:23 +01:00
parent 04599861c0
commit f95029d348
3 changed files with 39 additions and 0 deletions

View file

@ -125,6 +125,16 @@ public interface Node<T> {
*/ */
Optional<Node<T>> findChild(T child); 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. * Checks if the node is an ancestor.

View file

@ -246,6 +246,14 @@ public class NodeItem<T> implements Node<T> {
.findAny(); .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. * Checks if the node is an ancestor.
* *

View file

@ -901,4 +901,25 @@ public class NodeItemTest {
assertThat(child.getParent()).isSameAs(node); assertThat(child.getParent()).isSameAs(node);
assertThat(node.getChildren()).containsExactly(child); 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");
}
} }