Refactor test code and add some tests