Refactor and improve tests