Add tests and refactor some classes for better testability