Close resources on exception, refactor tests