Refactor code and add failure tests