Add tests and a few fixes for testability