refactor lifecycle listener code and tests that use it