Fix and refactor test code